laravel 资源 url 取决于型号?

laravel resource url depend on model?

我是运行这个模型、迁移、资源控制器的命令。 php artisan make:model QuestionAnswer -mc -r ..

资源路由 Route::resource('faq','QuestionAnswerController');

我的编辑功能

public function edit(QuestionAnswer $questionAnswer)
    {
        // return $questionAnswer;
        return view('backend.faq.edit',get_defined_vars());
    }

编辑路线 {{route('admin.faq.edit',$questionAnswer->id)}}

编辑功能return $questionAnswerreturn空

下图

当我更改资源路由如模型名称时 Route::resource('question-answer','QuestionAnswerController');

编辑函数return $questionAnswerreturnobject平均预期输出..

图片

问题

laravel 资源 url 取决于模型或什么? 如果我在 Route::resource('faq','QuestionAnswerController'); 的某处有误,请发表评论,我会删除我的问题..

Laravel resource 根据 url 示例生成婴儿车

Route::resource('faq','QuestionAnswerController');

// this will generate url like

Route::get('faq','QuestionAnswerController@index')->name('faq,index');
Route::post('faq','QuestionAnswerController@store')->name('faq,store');
Route::get('faq/{faq}','QuestionAnswerController@show')->name('faq,show');
Route::put('faq/{faq}','QuestionAnswerController@update')->name('faq,update');
Route::delete('faq/{faq}','QuestionAnswerController@destroy')->name('faq,destroy');

所以在控制器中你需要像这样接受faq

public function edit(QuestionAnswer $faq) // here $faq should match with route prams
{
        return $faq;
}

或者您可以将路线 url faq 更改为 questionAnswer 然后您的旧代码将起作用

ref link https://laravel.com/docs/8.x/controllers#actions-handled-by-resource-controller

因为你的路由参数是question_answer,所以把controller改成:

public function edit(QuestionAnswer $question_answer)
{
   dd($question_answer);
}

或者,您可以具体告诉资源路由参数应该命名的内容:

Route::resource('faq','QuestionAnswerController')
           ->parameters(['faq' => 'questionAnswer']);

现在您可以访问 $questionAnswer 作为参数:

public function edit(QuestionAnswer $questionAnswer)
{
   dd($questionAnswer);
}

Naming Resource Route Parameters的官方文档可以找到here