Reputation: 467
I'm just playing around with my code and notice that one of my controller is returning empty attributes but the other is returning my data fine.
I have two controllers, OneController and TwoController with both resource and same model in it. I use the php artisan make:controller OneController --model==MyModel
and php artisan make:controller TwoController --model==MyModel
. two different controller with similar model.
Both have
public function show(MyModel $myModel)
{
dd($myModel);
}
But only theOneController@show
is returning my data...
My links are like this
{{route('one.show', $myModel->id) }}
and
{{route('two.show', $myModel->id) }}
I also run php artisan route:clear
I change my TwoController@show
to show($id)
and it is working fine but I can't ignore that the same code is giving me different results and I want my code to be as clean as possible.
Is there any rule in Laravel 5.8 that you can only use One controller per model on a resource?
Am I missing something?
Thanks!
Upvotes: 0
Views: 1626
Reputation: 12460
You're injecting the model you want into your controller action, instead of fetching the record yourself using the ID parameter. Because you're using this you need to adhere to certain rules - read the route model binding documentation for more information.
Long story short: the name of the parameter in the route definition and the name of the argument in the controller action need to match in order for route model binding to take place - otherwise a new model instance will be passed to the method.
Because you're using the Route::resource()
method instead of defining routes yourself Laravel will automatically call the parameter by the path you pass in. You can verify this by running php artisan route:list
.
To achieve this with a resource you'll need to manually name the resource parameters, which would effectively be something like Route::resource('two', 'TwoController')->parameters(['two' => 'myModel'])
where myModel
would be your model name.
Upvotes: 3