Laravel Route Model Binding Return False Owner of The Post

167 Views Asked by At

Good morning/afternoon/evening!

I have 2 model, User and post

User.php

public function getRouteKeyName()
{
    return 'user_name';
}

public function posts()
{
    return $this->hasMany(Post::class, 'by_id', 'id');
}

I have two records in users table

|--------------------------------------------|
|   id   |   user_name   |   ...   |   ...   |
|--------------------------------------------|
|   1    |   megamanx    |   ...   |   ...   |  
|   2    |   black_zero  |   ...   |   ...   | // Edited

Post.php

public function getRouteKeyName()
{
    return 'slug';
}

public function by()
{
    return $this->belongsTo(User::class, 'by_id', 'id');
}

I have one record in posts table

|----------------------------------------------------|
|   id   |   by_id   |   slug              |   ...   |
|----------------------------------------------------|
|   1    |   1       |   test-first-post   |   ...   |  

In my route

Route::group(['prefix' => '{user}', function () {

    Route::get('/', function (User $user) {
        return View::make('user.index', compact('user'));
    });

    Route::get('/{post}', function (User $user, Post $post) {
        return View::make('post.index', compact('user', 'post'));
    });
});

As you can see I use Route model binding for User user_name and for Post slug

So when I visit the route, ex :

127.0.0.1:8000/megamanx/test-first-post
// it return the correct owner

user megamanx is the owner of the post (test-first-post)

But, when I try the user param to other user, ex :

127.0.0.1:8000/black_zero/test-first-post
// Hey you don't own that post!

And the owner post name change to black_zero, but he didn't own that post

So how to solve this? I want when the user try to change the user_name, to something else, return 404. because only user megamanx own post test-first-post

I'm always open to critics, cause I want to be a better developer, if there's any wrong in method above (Route, model, etc), please correct me!, thank you (・∀・)ノ

Sorry for bad english ( ̄▽ ̄*)ゞ

Thanks in advance!

0

There are 0 best solutions below