I'm trying to create a route model binding for two models: "User" and "Article"
Route::get('/{user}', 'UsersController@show');
Route::get('/{article}', 'ArticlesController@show');
Problem is, one of these will always take precedence over the other, depending on the order they are declared.
I want the user route to take precedence over the articles route if a user and an article happends to have the same route, but the problem is that laravel returns a 404 page when it does not match a user, even if the route should match an article.
I know that you can use the where() function with regex for this, however both of these models uses the same structure for the route key name (they are both strings). Can I make the regex search a database column or something?
You have 2 Options:
Route::get('/users/{user}', 'UsersController@show');
Route::get('/articles/{article}', 'ArticlesController@show');
RouteServiceProvider.php
:/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
parent::boot();
Route::bind('userOrArticle', function ($value) {
return is_numeric($value)
? App\User::where('id', $value)->firstOrFail()
: App\Article::where('title', $value)->firstOrFail();
});
}
Route::get('/{userOrArticle}', function ($userOrArticle) {
return $userOrArticle instanceof \App\User
? redirect()->action('UsersController@show', ['user' => $userOrArticle]);
: redirect()->action('ArticlesController@show', ['article' => $userOrArticle]);
});
See 'Customizing The Resolution Logic' section of the docs for more info: https://laravel.com/docs/master/routing#explicit-binding