Hashaam zahid
Hashaam zahid

Reputation: 325

Getting this action is unauthorized in laravel

I am getting This action is unauthorized 403 when i enter url localhost/website/post/1/edit. i want to protect to edit post from unauthorized user .

in PostController

public function edit($id)
{
$post=Post::findOrFail($id);
$this->authorize('check_access',$post);
return 'You are authorized';
}

In AuthServiceProvider.php

protected $policies = [
Post::class => 'PostPolicy::class',
];

in PostPolicy.php

public function check_access($post)
{
return Auth::user()->id==$post->user_id;
}

In web.php Route::resource('post','PostController');

Please Tell Where i am wrong . i am new in laravel and totally frustrated. Thanks

Upvotes: 0

Views: 2587

Answers (1)

nakov
nakov

Reputation: 14278

You should not be totally frustrated my friend. You should read the documentation for better understanding on the code you are trying to write. So just follow the example here and you should be all good to go. So instead of accessing the user from the Auth guard, you can pass it through to the method as first parameter.

public function check_access(User $user, Post $post)
{
    return $user->id == $post->user_id;
}

Upvotes: 2

Related Questions