是否可以在不使用 die() 的情况下从 Laravel Api 中的 'return chain' 发送响应?

Is possible to send a response from a 'return chain' in Laravel Api without using die()?

我有这个命令控制器。是否可以在不使用 die () 和 return 的情况下终止脚本以响应用户说所选择的方法不存在? 使用 die() 的方式是否正确?

我这里有这个例子:

    public function store(Order $order , Request $request)
    {
        $this->checkcart();
        $this->checkCountry( $request['form']['country'] ); // Can Return a response and kill the script
        $this->checkPayMethod( $request['form']['pay'] ); // Can Return a response and kill the script

        //create order, do calculations if the 3 methods above pass...
    }

    public function checkCountry ( $country ) {
        if ( ! in_array ( $country , country_list () ) ) {
            return $this->doesNotExist();
        }
    }

    public function checkPayMethod ( $pay) {
        if ( ! in_array ( $pay , pay_list () ) ) {
            return $this->doesNotExist();
        }
    }

    public function doesNotExist () {
        //response()->json(['error' => 'doesnot_exist','data' => 'doesnot_exist'] , 403 )->send();
        response()->json(['error' => 'doesnot_exist','data' => 'doesnot_exist'] , 403 )->send();
        die(); //Without Using Die ? 
    }

如果您不处理,则不能 return 子调用中的响应对象。

response() 对象应该return在路由器调用的主要方法上编辑。

我会这样做:

假设 store 是路由器的主要方法(我假设这是因为您在参数中有 Request 对象)

public function store(Order $order , Request $request)
{
    $check = $this->checkcart() && $this->checkCountry( $request['form']['country'] ) && $this->checkPayMethod( $request['form']['pay'] );

    if (!$check) {
        return response()->json(['error' => 'doesnot_exist','data' => 'doesnot_exist'] , 403 )->send();
    }

    //create order, do calculations if the 3 methods above pass...
}

然后确保您的所有调用都是 returning 布尔值(如果检查通过则为真,否则为假)

像这样:

public function checkCountry ( $country ) {
    return in_array($country , country_list());
}

public function checkPayMethod($pay) {
    return in_array($pay, pay_list());
}