是否可以不使用die()从Laravel Api中的“返回链”发送响应?

问题描述 投票:1回答:1

我有这个命令controller。是否可以在不使用die()的情况下杀死脚本,并向用户返回响应,说明所选择的方法不存在?使用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 ? 
    }

php laravel api response chain
1个回答
2
投票

如果不处理,则无法在子调用中返回响应对象。

一个response()对象用于在路由器调用的main方法上返回。

我会这样做:

假设存储是路由器的主要方法(我之所以这样是因为您在参数中有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...
}

然后确保您的所有呼叫都返回布尔值(如果通过检查,则为true,否则为false)

像这样:

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

public function checkPayMethod($pay) {
    return in_array($pay, pay_list());
}
© www.soinside.com 2019 - 2024. All rights reserved.