在laravel 5中使用slu ??

Mar*_*nJH 5 slug laravel-5

我在我的应用程序上做了雄辩的工作.S g保存得很好.Buuuut ...我如何用它来创建一个漂亮的网址?

如果可能的话,我想在我的网址中使用它们而不是ID号码.

The*_*pha 8

是的,您可以slug在您的route生成和生成中使用url,例如,如果您声明这样的路由:

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

然后在您的控制器中,您可以声明这样的方法:

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

username是你的slug,它必须是一个字符串,因为where()...在路由声明中.如果integer传递了一个然后route找不到并且404将抛出错误.


Cac*_*aco 6

从Laravel 5.2开始,如果使用Route Model Binding,则可以照常创建包含对象标识符的路由(Implicit Binding)。例如:

routes/web.php(Laravel 5.3)或app/Http/routes.php(Laravel 5.2)中:

Route::get('categories/{category}', 'CategoryController@show');
Run Code Online (Sandbox Code Playgroud)

在您的CategoryController

show (Category $category) {
    //
}
Run Code Online (Sandbox Code Playgroud)

您唯一需要做的就是告诉Laravel slug通过在雄辩的模型中自定义键名,从另一个列(例如column)中读取标识符:

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

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