简体   繁体   English

Laravel请求接收数组的策略

[英]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. 我在一个Request上遇到了一个问题,在其中我正在使用针对它的authorize()方法的策略。 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. 它从输入请求中接收一个ID数组,然后我将其用于从数据库中获取ID,并且我必须确认这些记录之一中的一个名为Seller_id的字段是否与登录的用户匹配。 If so, o have to return false and i cannont keep on executing the job, if not i keep going. 如果是这样,则o必须返回false,并且我不能继续执行该作业,否则我将继续前进。 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;
    }

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. 否则,在函数末尾返回true。

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM