Search code examples
phplaravelapiresponsechain

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


I have this order controller. Its possible to kill the script without using die () and return an response to the user saying that the method picked doesn't exist ? Is using die() the right way ?

I have this example here :

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


Solution

  • you can't return a response object in a sub call if you don't handle it.

    A response() object is meant to be returned on the main method that has been called by the router.

    I would do that:

    Assuming that store is your main method from the router (I assume this because you have the Request object in params)

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

    Make sure then that all your calls are returning boolean (true if check passed and false otherwise)

    like this:

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