Using slugs in laravel 5?

I have done an eloquent job in my application. Plums keep just fine. Buuuut ... How do I use it to generate a pretty url?

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

+3


source to share


2 answers


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

.

+6


source


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

.

See Laravel 5.3 (or 5.2) Fitting a Route Model

+2


source







All Articles