Wisamx
Wisamx

Reputation: 303

laravel error when explicit model binding on route group

I wrote this route group

Route::group(['prefix' => 'admin/{store}',  'middleware' => ['auth', 'SetStoreId'], 'namespace' => 'Admin'], function (App\Models\Store $store) {

Route::get('/', 'DashboardController@index');

Route::resources([
    '/vocabulary' => 'VocabularyController',
    '/term' => 'TermController',
]);

});

and accessed this url

http://localhost/SyriaShop/public/admin/1/vocabulary

then I get this error message

Type error: Argument 1 passed to Illuminate\Routing\Router::{closure}() must be an instance of App\Models\Store, instance of Illuminate\Routing\Router given, called in E:\wamp\www\SyriaShop\vendor\laravel\framework\src\Illuminate\Routing\Router.php on line 390

although when I use this config (without model binding)

Route::group(['prefix' => 'admin/{storeId}',  'middleware' => ['auth', 'SetStoreId'], 'namespace' => 'Admin'], function ($storeId)

everything work well!

Upvotes: 0

Views: 531

Answers (2)

lagbox
lagbox

Reputation: 50481

The closure passed to Route::group gets called with an instance of the router passed to it (you don't control this as you are not the caller).

The actions for these routes in this group would be taking this route parameter, store, in their definitions.

If you don't want all these controller methods to need to take this route parameter you can remove this parameter from the route. (In that recently created middleware would be a good place)

$request->route()->forgetParameter('store');

This should remove the need for these controller methods to take this route parameter and you are already dealing with this route parameter in your middleware.

Upvotes: 1

Pol Lluis
Pol Lluis

Reputation: 1162

That kind of implicit Model binding will work if the primary key of your table is 'id', since your code looks good I think that most probably your table doesn't have the column 'id' as primary key.

If that is the case you can override it using the following function on your model:

public function getRouteKeyName()
{
    return 'slug';
}

Hope that's the case!

Upvotes: 0

Related Questions