Laravel Controller Type Hinting

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



Laravel Controller Type Hinting



After creating a model with -mcr (php artisan make:model Institution -mrc), the show function in controller was scaffolded as:


/**
* Display the specified resource.
*
* @param AppOrganizationInstitution $institution
* @return IlluminateHttpResponse
*/
public function show(Institution $institution)

return view('institutions.show', ['institution' => $institution]);



The return view... was inserted by me. I was expecting it to have it populated with the object whose id was sent in the parameters.


/institutions/1



But, after using dd($institution), I verified that it has the ID, not the object.



Shouldn't this variable return me the object?





can you put as your dd output here?
– kallosz
Aug 8 at 13:54





How is your route defined for show?
– pseudoanime
Aug 8 at 13:54




2 Answers
2



This is called Route Model Binding. Your route will need to look something like:


Route::get('institutions/institution', 'InstitutionController@show');



and then as per your controller


public function show(Institution $institution)

return view('institutions.show', compact($institution))



You can read more on this here.



I imagine your route had the parameter called id rather than institution.


id


institution



Replace the parameter of show function


public function show(Institution $institution)

return view('institutions.show', compact($institution))



becomes


public function show($id)

$institution = AppInstitution::findOrFail($id);;
return view('institutions.show', compact('institution'));



and in your routes
Route::get('institutions/id', 'InstitutionController@show');


Route::get('institutions/id', 'InstitutionController@show');






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Firebase Auth - with Email and Password - Check user already registered

Dynamically update html content plain JS

How to determine optimal route across keyboard