How to generate slug in laravel ??

Discussion for various published PHP frameworks, including Zend Framework, CodeIgniter, Kohana, CakePHP, Yii, Symfony, and others.

Moderator: General Moderators

Post Reply
User avatar
gautamz07
Forum Contributor
Posts: 331
Joined: Wed May 14, 2014 12:18 pm

How to generate slug in laravel ??

Post by gautamz07 »

I currently have the following foreach loop running on the index page of my application:

Code: Select all

@foreach($recentPost as $recent)

	<div class="col-md-6">
		<div class="indi-news-highlight-box">
			<a href="{!!  route('getArticle' , ['id' => $recent->id ]) !!}">
				<img src="{{ URL::asset('images/temp/blog-post-image.jpg') }}" alt="{!!  $recent->title  !!}">
			</a>
			<div class="content-box">
				<h3>
					<a href="{!!  route('getArticle' , ['id' => $recent->id ]) !!}">
						{{  $recent->title }}
					</a>
				</h3>
				<p>
					{{ $recent->blog_content }}
				</p>
			</div>		
		</div>
	</div>   <!-- End col-md-6 -->

@endForEach
Now as you can see the anchor tags are populated with the id which is numbers like 1,2,3 etc...

so i have the following route in my route file:

Code: Select all

Route::get('/{id}' , [
	'uses' => 'PagesController@show',
	'as' => 'getArticle'
]);
and then the following method in my pagesController:

Code: Select all

public function show($id) {
	return view('pages.article' , ['article' => Admin::findOrFail($id)]);
}
So now when i click on the links i get urls like so:
http://localhost:8080/laravel-blog/public/6
http://localhost:8080/laravel-blog/public/1

and so on.. but what i really want is the slug of the article , so say the article title is 'firefox browser bug' ,

i want the url to be:
http://localhost:8080/laravel-blog/publ ... rowser-bug

How do i do this ??

Thank you.
Gautam.
User avatar
Celauran
Moderator
Posts: 6425
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: How to generate slug in laravel ??

Post by Celauran »

Do you have such a route defined? What have you tried so far?
User avatar
gautamz07
Forum Contributor
Posts: 331
Joined: Wed May 14, 2014 12:18 pm

Re: How to generate slug in laravel ??

Post by gautamz07 »

What should i search for on google , i am not sure .. and if i want a slug .. instead of an ID , what exactly do i insert in the href of the anchor tag ? i am currently doing :

Code: Select all

<a href="{!!  route('getArticle' , ['id' => $recent->id ]) !!}">
can you give me a hint :P
User avatar
Celauran
Moderator
Posts: 6425
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: How to generate slug in laravel ??

Post by Celauran »

Do you understand how routing works? How Eloquent models work? I'd read up on those first. Think about what you're trying to do, what your find needs to look like, what parameters you need to pass to accomplish that.
Post Reply