laravel resource url depend on model?

与世无争的帅哥 提交于 2020-12-15 05:23:30

问题


i am run this command for model, migration, resource controller. php artisan make:model QuestionAnswer -mc -r ..

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

My Edit Function

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

Edit Route {{route('admin.faq.edit',$questionAnswer->id)}}

Edit function return $questionAnswer return null

Below Picture

When i Change resource route like model name Route::resource('question-answer','QuestionAnswerController');

edit function return $questionAnswer return object mean expected output ..

Picture

Question

laravel resource url depend on model or something ? if i am wrong somewhere for Route::resource('faq','QuestionAnswerController'); please comment i will remove my question..


回答1:


Bacause your route parameter is question_answer, so change the controller to :

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

Alternatively, you can specifically tell the resource what the route parameter should be named :

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

Now you can access $questionAnswer as parameter :

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

The official documentation of Naming Resource Route Parameters will be found here




回答2:


Laravel resource generate prams base on url example

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

so here in controller you need to accept that faq like this

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

or you can change route url faq to questionAnswer then your old code will work

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



来源:https://stackoverflow.com/questions/64999075/laravel-resource-url-depend-on-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!