【问题标题】:how to fix Argument 2 passed to App\Http\Controllers\Posts\PostsController::show() must be an instance of App\Post, string given如何修复传递给 App\Http\Controllers\Posts\PostsController::show() 的参数 2 必须是 App\Post 的实例,给定字符串
【发布时间】:2019-09-26 10:54:12
【问题描述】:

我是 laravel 的新手。你能帮助我吗?我不明白问题出在哪里:

参数 2 传递给 App\Http\Controllers\Posts\PostsController::show() 必须是一个实例 App\Post 的,给定的字符串

后控制器

public function show( Category $category  , Post $post )
{

        return view('posts.post',[

            'post' => $post,

        ]);

}

模型 Post.php

class Post extends Model
{


    protected $fillable = ['user_id','category_id','name','slug','body'];
    protected $with = ['user','category'];

    protected static function boot()
    {
        parent::boot(); // TODO: Change the autogenerated stub
        self::creating(function($model){
            $model->slug = str::slug($model->name);
        });
    }

    public function path()
    {
        return "/blog/{$this->category->slug}/{$this->id}";
    }

    public function user ()
    {
        return $this->belongsTo(User::class);

    }//

    public function category ()
    {
        return $this->belongsTo(category::class);

    }
}

Web.php

route::group(['namespace'=>'Posts','prefix' => 'blog'], function (){

    route::get('','PostsController@index')->name('blog');
    route::get('{Category}','PostsController@index');
    route::get('{Category}/{post}','PostsController@show')->name('post');
});

【问题讨论】:

    标签: php laravel


    【解决方案1】:

    更改路线中的参数。将Category 更改为category

    Route::get('{category}/{post}','PostsController@show')->name('post');
    

    或者让两个参数都以大写字母开头。

    Route::get('{Category}/{Post}','PostsController@show')->name('post');
    

    或第一个以小写字母开头

    Route::get('{category}/{Post}','PostsController@show')->name('post');
    

    【讨论】:

      【解决方案2】:

      public function show( Category $category , Post $post )

      以上行告诉show函数接收的第一个参数将是Category的实例,第二个参数将是Post的实例

      所以你在使用路线时需要注意:

      route::get('{Category}/{post}','PostsController@show')->name('post');
      

      始终满足这些条件。

      如果您不确定,那么只需删除类型转换,以便参数可以是 any 类型,如下所示:

      public function show ($category, $post)
      

      【讨论】:

        猜你喜欢
        • 2019-06-04
        • 2020-07-14
        • 2015-07-13
        • 2023-03-09
        • 2017-09-26
        • 1970-01-01
        • 2020-02-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多