Your Location is: Home > Php

Laravel explicit route mode binding not working in some cases?

From: Luxembourg View: 4240 Jan 

Question

I am using Laravel 8 and explicit route mode binding in my project to call an product under the slug instead of the id. I have products, posts and etc, which are all using explicit route mode binding with the slug in the database instead of the id.

What really confuses me is that the explicit route mode binding is working everywhere but not with products. Here is my RouteServiceProvider:

// Change route for product from $id to $slug
Route::bind('product', function ($value) {
    return Product::where('slug', $value)->first() ?? abort(404);
});

// Change route for user from $id to $name
Route::bind('user', function ($value) {
    return User::where('name', $value)->first() ?? abort(404);
});

// Change route for product from $id to $slug
Route::bind('post', function ($value) {
    return Post::where('slug', $value)->first() ?? abort(404);
});

Here are some example routes for a user, a product and a post:

works:      Route::get('/product/{productType}/{product}', ['as' => 'product.show', 'uses' => '[email protected]']);     
404 error:  Route::post('product/{product}/like', ['as' => 'product.like', 'uses' => '[email protected]']);          
404 error:  Route::post('product/{product}/dislike', ['as' => 'product.dislike', 'uses' => '[email protected]']); 
404 error:  Route::post('product/{product}/mark', ['as' => 'product.mark', 'uses' => '[email protected]']);

works:      Route::get('user/{user}', ['as' => 'user.show', 'uses' => '[email protected]']);
works:      Route::post('user/{user}/update/password', ['as' => 'user.password.change', 'uses' => '[email protected]']);

works:      Route::get('/blog/{postCategory}/{post}', ['as' => 'post.show', 'uses' => '[email protected]']);

When I do a dd for the value in the RouteServiceProvider for user, product and post I can figure out what's the problem here. All values do dump the actual slug of the resource. Even the get request for a product is the actual slug. However, when performing an post request for a product, I always get the end of the url as value. Of course this leads to a 404.

For example the route product/{product}/mark with an post requests does dump mark as value and not the slug of the product... why is that? All other post requests work fine!

I also tried switch a route from a post method to a get method but same result here... also an 404 error and I get mark as value again...

Can anybody explain whats the problem here and why it is not working?

When I change product/{product}/mark to produkt/{product}/mark it is working. But why? and why is '/product/{productType}/{product}' working? That is really strange..

Kind regards and thank you!

Best answer

I have now removed my changes in the RouteServiceProvider and I am using this function which is provided since Laravel 8. Problem solved... I don't know what the problem was..