一中常见的路由模式,就是在控制器方法中先通过参数 ID 查找对应的模型(或资源)。
Route::get('conferences/{id}', function ($id) {$conference = Conference::findOrFail($id);});
laravel 提供了 路由模型绑定 来处理这种问题。你可以指定参数的类型是模型名(如 Conference $conference),这样在每次访问路由时, laravel 会通过 ID 找到对应的模型(数据库记录),传递该记录给闭包或者控制器中的方法。
- 显式的使用路由模型绑定
Route::get('conferences/{conference}', function (Conference $conference) {
return view('conferences.show')->with('conference', $conference);
});
ps: 路由模型绑定时,默认查找的是主键(ID),你可以在模型中修改为,你自己需要的列,只需在模型中增加如下方法
// 查找时,会使用 slug 列 public function getRouteKeyName() { return 'slug'; }
- 隐式的使用路由模型绑定
// 在 App\Providers\RouteServiceProvider 的 boot() 方法中 增加一行
public function boot()
{
// Just allows the parent's boot() method to still run
parent::boot();
// Perform the binding
Route::model('event', Conference::class);
}
现在,任何带有 {event} 参数的路由,都会被路由模型绑定的逻辑所处理,即根据 id 查找到 Conference 并返回给闭包或方法。
// eg:
Route::get('events/{event}', function (Conference $event) {
return view('events.show')->with('event', $event);
});
