Using slugs in laravel 5?
Yes, you can use slug
in 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 can declare a method like this:
public function profile($username)
{
$user = User::where('username', $username)->first();
}
username
- this is your slug here and it should be a string because of where()...
in the route declaration. If passed integer
, it route
cannot be found and an error will be thrown 404
.
source to share
As of Laravel 5.2, if you are using route model binding, you can make your routes contain an object id 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 CategoryController
:
show (Category $category) {
//
}
The only thing you need to do is tell Laravel to read the ID from another column, like a column slug
, by customizing the key name in your eloquent model:
/**
* Get the route key for the model.
*
* @return string
*/
public function getRouteKeyName()
{
return 'slug';
}
You can now reference your own url
, which requires an object id with an id slug
instead id
.
source to share