0

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;
    }
Luiz Wynne
  • 460
  • 3
  • 10
  • 28
  • You basically want to verify that all tickets submitted through the form belong to the seller? – Dan May 08 '19 at 12:07
  • Yes, or if that works, if some of the ticket->seller_id from those tickets match the user id i return false – Luiz Wynne May 08 '19 at 12:10

1 Answers1

2

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;
}
Dan
  • 5,140
  • 2
  • 15
  • 30