Using slugs in laravel 5?

前端 未结 2 1409
别跟我提以往
别跟我提以往 2020-12-09 22:40

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

2条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-09 23:07

    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.

提交回复
热议问题