简体   繁体   中英

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

The category.blade does not output {‌{$categories->name}} . No errors are shown. If I change the {‌{$categories->name}} and type normal text eg 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.

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM