Laravel 5.6 getRouteKeyName()无法正常工作 [英] Laravel 5.6 getRouteKeyName() not working

查看:133
本文介绍了Laravel 5.6 getRouteKeyName()无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我到目前为止的代码:

This is the code I have so far:

Web.php

Route::get('/{uri}', 'PageController@show')->name('page.show');

PageController

PageController

// Show the requested page
public function show(Page $page)
{
    return view('templates.page', compact('page'));
}

页面模型

public function getRouteKeyName()
{
    return 'uri';
}

我的问题是,即使我更改了路由键名,Route-model-binding为何仍无法正常工作并且无法在控制器中找到页面.它只是控制器中有一个空模型,没有找到页面.

My question is how come the Route-model-binding is not working and not finding the page in the controller even though I have changed the route key name. It just has an empty model in the controller and has not found the page.

推荐答案

您应该执行以下操作:

// 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,并且您的页面表具有id列,则说明已完成,但是如果您要查询页面表(而不是id),则声明getRouteKeyName方法在Page模型中,然后从该方法中检索该列名称.因此,例如,如果您的页面表具有唯一的slug,而您的uri具有类似example.com/contact的内容,则声明以下方法:

If /{page} contains an id like: 1 and your pages table has id column then all done but if you would like to query the pages table other than an id then declare the getRouteKeyName method in your Page model and retuen that column name from that method. So for example, if your pages table has unique slug and your uri has something like example.com/contact then declare the following method:

public function getRouteKeyName()
{
    return 'slug'; // db column name
}

现在,框架将使用where slug = {slug from uri}/default以外的类似where slug = {slug from uri}的内容来查询页面.希望它能对您有所帮助.

Now, the framework will query for a page using something like where slug = {slug from uri} other than id/default. Hope it helps now.

这篇关于Laravel 5.6 getRouteKeyName()无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆