Lewis Tudor
Lewis Tudor

Reputation: 77

Resource Controller methods with model as parameter not working

As in the basic Laracasts.com tutorial (Laracast 5.7 from scratch) I'm trying to use the following methods public function show(prototypes $prototypes) parameter to construct a view. However my view is created correctly but $prototypes is null.

The route works well(/prototypes/1/edit) and I ensured that a prototype object with the id 1 exists. I found some older solution which stated to use something like (integer $id) as parameter but this leads to some more code. It should work like this:

Controller:

public function edit(prototypes $prototypes)
{
    //
    return view('prototypes.edit', compact('prototypes'));
}

According to Laracast From Scratch this should work.

Do you know how I could fix this?

What mechanism is behind this that the prototypes.edit method knows how to use the correct parameter?

Upvotes: 0

Views: 1877

Answers (2)

dparoli
dparoli

Reputation: 9161

For the Implicit Model Binding to works the injected variable name should match the route parameter name, in your case I think that your parameter name could be {prototype}, you can verify it by issuing the command php artisan route:list in the console.

If that is true you have to change the variable name to $prototype (please note the singular) in your controller function to match the parameter name {prototype}, like this:

public function edit(prototypes $prototype)
{
   return view('prototypes.edit', compact('prototype'));
}

Update: BTW the laravel convention on Model's name is singular camel case, in your case your Model should be named Prototype not prototypes, i.e.:

public function edit(Prototype $prototype)
{
   return view('prototypes.edit', compact('prototype'));
}

Upvotes: 5

Watercayman
Watercayman

Reputation: 8178

In order to inject the Prototypes model into the controller variable $prototypes, Laravel is expecting a matched name from the route to the input of the method. So in your routing, this:

 /prototypes/1/edit

Needs to be

 /prototypes/{prototypes}/edit

in order for the edit method to inject the correct instance of your prototypes model.

Upvotes: 0

Related Questions