5

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?

Victor Ribeiro
  • 577
  • 7
  • 20

2 Answers2

13

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

Kenny Horna
  • 13,485
  • 4
  • 44
  • 71
Munch
  • 739
  • 7
  • 19
  • 1
    The name of the route param, and the name of the param being passed to the controller's method must be the same for this to work. – kaeland Jul 11 '21 at 09:43
3

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

afikri
  • 384
  • 4
  • 10