路由模型绑定问题 [英] Route model binding issue
问题描述
我有一组代码,它与我正在使用的其他代码相似,并且工作正常.就在这种情况下,存在一些我无法找到原因的神秘问题.请参见下面的代码
I have a set of code, it is similar to the other codes that I'm using and they are working fine. Just in this case there is some mysterious issue which I'm not able to find the cause of. Please see the code below
BlogPostController.php
public function category(Category $category){
return view('blog/cat')->with('categories',$category);
}
categories.blade.php
@extends('layouts.blog')
{{$categories->name}}
category.blade
不输出{{$categories->name}}
.没有显示错误.如果我更改{{$categories->name}}
并键入普通文本,例如data
,则data
会打印在网页上.我什至尝试重新启动系统.没有出路.
The category.blade
does not output {{$categories->name}}
. No errors are shown. If I change the {{$categories->name}}
and type normal text e.g data
, then data
is printed on the webpage . I even tried restarting my system. There is no way out.
我删除了模型路由绑定",并尝试了通常的方法,
The I removed the Model Route Binding, and tried the usual way ,
public function category($id){
$category = Category::where('id',$id)->first();
return view('blog/cat')->with('categories',$category);
}
编辑 路线-web.php
Route::get('blog/category/{cat}','BlogPostController@category')->name('blog.category');
在这种情况下,category.blade.php
会正确打印数据.
In this case the category.blade.php
prints the data properly.
在这种情况下,模型路由绑定可能是什么问题.我所有的控制器都使用模型路由绑定,而不是通常的方式,但这是我第一次遇到这个问题.
What could be the issue with the Model Route Binding in this case. All my controllers use Model Route Binding rather than the usual way, but this is the first time I'm stumbling upon this issue.
推荐答案
要注册显式绑定,请使用路由器的model方法为给定参数指定类.您应该在RouteServiceProvider类的启动方法中定义您的显式模型绑定
To register an explicit binding, use the router's model method to specify the class for a given parameter. You should define your explicit model bindings in the boot method of the RouteServiceProvider class
或使用显式绑定
RouteServiceProvider.php
RouteServiceProvider.php
public function boot()
{
parent::boot();
Route::model('cat', App\Category::class);
}
您仍然可以使用:
Route::get('blog/category/{cat}','BlogPostController@category')->name('blog.category');
这篇关于路由模型绑定问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!