Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Route model binding and parent child validation in Laravel

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?

like image 650
Ben Fransen Avatar asked Sep 08 '25 01:09

Ben Fransen


1 Answers

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);
        });
    }
}
like image 72
Mehdi Avatar answered Sep 10 '25 09:09

Mehdi