Say I have a route like:
Route::get('users/{user}/posts/{post}', 'PostController@show')
And I've set up Route Model binding for an App\User
to {user}
and an App\Post
to {post}
. I've seen I'm able to call whatever existing post for any given user to get contents on the screen. Is there a generic place where I can assign constraints to the bound models?
you can use Route::bind
and set a second variable for the function to access the current route and it parameters like this:
class RouteServiceProvider extends ServiceProvider{
public function boot(Router $router)
{
$router->bind('user', function($value) {
return App\User::findOrFail($value);
});
$router->bind('post', function($value, $route) {
return $route->parameter('user')->posts()->findOrFail($value);
});
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With