skip to Main Content

If I have route like this.

Route::get('/users/{user}/posts/{post}', function (User $user, Post $post) {
    return $post;
});

Then If User id 1 has Post id 1,2,3 and User id 2 has Post id 4,5,6.

How to make Post that bind in route return 404. When Post was not create by User like /users/1/posts/4.

2

Answers


  1. Chosen as BEST ANSWER

    So the point is I used scopeBindings chain from Route::resource. So it didn't work

    It have to use this way

    Route::scopeBindings()->group(function () {
        Route::resource('users.posts', UserPostController::class);
    });
    

    It work perfectly.


  2. If you wish, you may instruct Laravel to scope "child" bindings even when a custom key is not provided. To do so, you may invoke the scopeBindings method when defining your route:

    use AppModelsPost;
    use AppModelsUser;
     
    Route::get('/users/{user}/posts/{post}', function (User $user, Post $post) {
        return $post;
    })->scopeBindings();
    
    /users/1/posts/1 <- returns the post 1
    /users/1/posts/4 <- returns 404
    /users/2/posts/4 <- returns the post 4
    /users/2/posts/1 <- returns 404
    

    Documentation

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search