7

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.

MartinJH
  • 2,590
  • 5
  • 36
  • 49
  • Basically everything boils down to your routes. You still need to create your routes specifying slugs E.g `Route::get('/home/{slug}' , function(){ });` – Emeka Mbah Jun 11 '15 at 17:39

3 Answers3

10

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.

The Alpha
  • 143,660
  • 29
  • 287
  • 307
9

As of Laravel 5.2, if you use Route Model Binding, then you can make your routes that contain the object identifier as usual (Implicit Binding). For example:

In routes/web.php (Laravel 5.3) or app/Http/routes.php (Laravel 5.2):

Route::get('categories/{category}', 'CategoryController@show');

In your CategoryController:

show (Category $category) {
    //
}

The only thing you need to do is telling Laravel to read the identifier from a different column like, for example, slug column, by customizing the key name in your eloquent model:

/**
 * Get the route key for the model.
 *
 * @return string
 */
public function getRouteKeyName()
{
    return 'slug';
}

Now, you can refer your url's that requires the object identifier with the slug identifier instead the id one.

See Laravel 5.3 (or 5.2) Route Model Biding

Caco
  • 1,601
  • 1
  • 26
  • 53
2

For future readers, as of Laravel 8.0, you can specify a column right in the path

Route::get('/users/{user:slug}', function (User $user) {
    return $user->bio;
});
gfaster
  • 157
  • 2
  • 12