Koe
Koe

Reputation: 1

Policy always returns 403 even if the method returns true in Laravel 11

why does my controller actions always returns a 403 even if the policy returns true?

I'm using Laravel 11, I have BoardItemFile model and BoardItemFilePolicy. Even if the conditions are met, it still returns 403.

What I did:

my policy:

class BoardItemFilePolicy
{
    public function before(User $user, string $ability) : bool | null {
        if ($user->userRole->role == 0) {
            return true;
        }

        return null;
    }

    public function create(User $user, BoardItem $item): bool
    {
        return true;
       // return $user->id == $item->user_id;
    }

and the controller method:

class BoardItemFileController extends Controller
{
    public function index(Workspace $workspace, Board $board, BoardItem $item)
    {
        $boardItemFiles = $item->files;
        return response()->json(["data" => $boardItemFiles]);
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request, Workspace $workspace, Board $board, BoardItem $item)
    {
        // dd($item, $request->user());
        if ($request->user()->cannot('create', $item)) {
            abort(403);
        }
        $request->validate([
            "files" => ['required', 'array'],
            "files.*" => ['file', 'image', 'max:10240']
        ]);
        ...

I also tried Gate::authorize('create', [$item]) and returns the same thing.

I'm not sure why this particular policy fails as I have more policy which works fine and expected.

Upvotes: 0

Views: 42

Answers (0)

Related Questions