Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using slugs in laravel 5?

Tags:

slug

laravel-5

I have made eloquent-sluggable work on my app. Slugs are saved just fine. Buuuut... How do I use it to create a pretty url?

If possible, I would like to use them in my url instead of ID numbers.

like image 291
MartinJH Avatar asked Jun 11 '15 17:06

MartinJH


People also ask

What is the use of slug in laravel?

Slug is a part of a URL that identifies a particular (unique) web page. An example of a slug is URL https://codelapan.com/post-slug, and means the slug of that URL is "post-slug". For SEO, include keywords in the URL and create a user-friendly URL.


1 Answers

Yes, you can use slug in your route and generated url, for example, if you declare a route something like this:

Route::get('users/{username}', 'UserController@profile')->where('profile', '[a-z]+');

Then in your controller, you may declare the method like this:

public function profile($username)
{
    $user = User::where('username', $username)->first();
}

The username is your slug here and it must be a string because of where()... in the route declaration. If an integer is passed then route couldn't be found and 404 error will be thrown.

like image 79
The Alpha Avatar answered Oct 11 '22 08:10

The Alpha