Search code examples
laravellaravel-livewire

basic authorization with livewire and laravel


I have a method in my postpolicy that only current authenticated user can delete his own posts. I try to put this method in my delete method, but it returns that the method does not exist. I have included authroizerequest in the controller, so I'm confused why I get this error.

Method App\Http\Livewire\Posts::authorize does not exist.

use Illuminate\Foundation\Auth\Access\AuthorizesRequests;

   public $postId = null;

public function deletePost($id)
    {
        
        $this->authorize('delete', $this->postId);
        $post = Post::find($id);
        Storage::delete('public/photos/', $post->image);
        $post->delete();
        session()->flash('flash.banner', 'Post Deleted Successfully');
    }

the policy:

    namespace App\Policies;

use App\Models\Post;
use App\Models\User;
use Illuminate\Auth\Access\HandlesAuthorization;

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

Solution

  • You are just importing use AuthorizesRequests trait not including this trait inside your class you need to use this trait inside your controller

    class ControllerName extends Controller {
      use AuthorizesRequests;
    }
    

    Using this way you can use AuthorizesRequest traits method inside your class.