Route model binding issue

2019-08-29 05:36发布

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}}

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);
}

EDIT ROUTE - web.php

Route::get('blog/category/{cat}','BlogPostController@category')->name('blog.category');

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.

2条回答
兄弟一词,经得起流年.
2楼-- · 2019-08-29 05:58

https://laravel.com/docs/5.5/routing#implicit-binding

Route::get('blog/category/{category}','BlogPostController@category')->name('blog.category');
查看更多
Anthone
3楼-- · 2019-08-29 06:10

From: laravel.com/docs/5.8/routing#route-model-binding

Implicit Binding

Laravel automatically resolves Eloquent models defined in routes or controller actions whose type-hinted variable names match a route segment name.

So try to do:

Route::get('blog/category/{category}','BlogPostController@category')->name('blog.category');

Explicit Binding

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

Or use Explicit Binding

RouteServiceProvider.php

public function boot()
{
    parent::boot();

    Route::model('cat', App\Category::class);
}

And you can still use:

Route::get('blog/category/{cat}','BlogPostController@category')->name('blog.category');
查看更多
登录 后发表回答