Search code examples
phplaravellaravel-request

Laravel Policy on Request receiving a array


I am facing a problem on a Request in which i am using a policy on it's authorize() method. It receives an array of IDs from the input request , which i then use for getting those from the DB and i have to confirm if a field called seller_id from one of those records matches the user logged. If so, o have to return false and i cannont keep on executing the job, if not i keep going. Not sure if i can pass that array as parameter so i tried the following option, which doesnt work. Any suggestions?

on the Request

public function authorize()
    {
        //return true;
        $tickets = Ticket::find(request()->input('tickets_ids'))->get();
        foreach($tickets as $ticket){
            return request()->user()->can('buyTicket', $ticket);
        }


    }

on the Policy

public function buyTicket(User $user, Ticket $ticket){
        if($user->id !== $ticket->seller_id){
            return true;
        }
        return false;
    }

Solution

  • Modify your request so it only aborts the loop if the current user can't buy the ticket. Otherwise, return true at the end of the function.

    public function authorize()
    {
        $tickets = Ticket::findMany(request()->input('tickets_ids', []))->get();
    
        foreach ($tickets as $ticket) {
            $userCanBuyTicket = request()->user()->can('buyTicket', $ticket);
    
            if (!$userCanBuyTicket) {
                return false;
            }
        }
    
        return true;
    }