Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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  \App\Organization\Institution  $institution
 * @return \Illuminate\Http\Response
 */
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?

like image 648
Victor Marconi Avatar asked Dec 07 '22 14:12

Victor Marconi


2 Answers

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

like image 174
Munch Avatar answered Dec 25 '22 18:12

Munch


Replace the parameter of show function

public function show(Institution $institution) 
{
    return view('institutions.show', compact($institution))
}

becomes

public function show($id) 
{
    $institution = App\Institution::findOrFail($id);;
    return view('institutions.show', compact('institution'));
}

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

like image 33
afikri Avatar answered Dec 25 '22 17:12

afikri