Laravel 5.6 getRouteKeyName() 不工作
Laravel 5.6 getRouteKeyName() not working
这是我目前的代码:
Web.php
Route::get('/{uri}', 'PageController@show')->name('page.show');
页面控制器
// Show the requested page
public function show(Page $page)
{
return view('templates.page', compact('page'));
}
页面模型
public function getRouteKeyName()
{
return 'uri';
}
我的问题是为什么即使我更改了路由键名称,路由模型绑定仍无法正常工作并且无法在控制器中找到页面。它只是在控制器中有一个空模型并且没有找到页面。
您应该执行如下操作:
// Route
Route::get('/{page}', 'PageController@show')->name('page.show');
// Controller Method
public function show(Page $page)
{
return view('templates.page', compact('page'));
}
如果 /{page}
包含一个 id
,例如:1
并且您的页面 table 有 id
列,那么一切都完成了,但是如果您想查询除 id 之外的页面 table 然后在您的 Page
模型中声明 getRouteKeyName
方法,并从该方法中返回该列名称。因此,例如,如果您的页面 table 具有独特的 slug
并且您的 uri
具有类似 example.com/contact
的内容,则声明以下方法:
public function getRouteKeyName()
{
return 'slug'; // db column name
}
现在,框架将使用类似 where slug = {slug from uri}
而非 id
/default 的方式查询页面。希望现在对您有所帮助。
这是我目前的代码:
Web.php
Route::get('/{uri}', 'PageController@show')->name('page.show');
页面控制器
// Show the requested page
public function show(Page $page)
{
return view('templates.page', compact('page'));
}
页面模型
public function getRouteKeyName()
{
return 'uri';
}
我的问题是为什么即使我更改了路由键名称,路由模型绑定仍无法正常工作并且无法在控制器中找到页面。它只是在控制器中有一个空模型并且没有找到页面。
您应该执行如下操作:
// Route
Route::get('/{page}', 'PageController@show')->name('page.show');
// Controller Method
public function show(Page $page)
{
return view('templates.page', compact('page'));
}
如果 /{page}
包含一个 id
,例如:1
并且您的页面 table 有 id
列,那么一切都完成了,但是如果您想查询除 id 之外的页面 table 然后在您的 Page
模型中声明 getRouteKeyName
方法,并从该方法中返回该列名称。因此,例如,如果您的页面 table 具有独特的 slug
并且您的 uri
具有类似 example.com/contact
的内容,则声明以下方法:
public function getRouteKeyName()
{
return 'slug'; // db column name
}
现在,框架将使用类似 where slug = {slug from uri}
而非 id
/default 的方式查询页面。希望现在对您有所帮助。