阅读(3924) (2)

Laravel 8 通过 Eloquent 模型填充参数

2021-06-24 14:19:40 更新

如果你要重定向到使用从 Eloquent 模型填充「ID」参数的路由,可以简单地传递模型本身。ID 会被自动提取:

// 对于具有该URI的路由: profile/{id}
return redirect()->route('profile', [$user]); 

如果你想要自定义这个路由参数中的默认参数名,需要重写模型实例上的 getRouteKey 方法或者指定路由参数 (profile/{id:slug}):

/**
 * 获取模型的路由键
 *
 * @return mixed
 */
public function getRouteKey()
{
    return $this->slug;
}