1

I have a problem with saving cookie before redirecting, example code:

class Example extends Controller{

    public function index(){

        Cookie::queue('examplecookie', 1, 525600);

        $this->next();
    }


    public function next(){


        $this->redirect();

        /* Prevent this part for loading after redirect
        *
        *  OTHER CODE ...
        */ 

    }


    public function redirect(){

        header('Location: http://someurl.com');

    }
}

If I am using die() after header location PHP is stopped browser is redirected and the cookie is not saved, and if die not exist browser is redirected, cookies is saved, but PHP still goes to other code. Also when using redirect() other code is loaded. Example:

public function redirect(){

    return \redirect('http://someurl.com')->send();

}

This class is an example of logic, real code is more complicated :). I want to save cookies, redirect and prevent PHP to go on other code.

Laky
  • 745
  • 2
  • 12
  • 25

2 Answers2

2

To return a response that ends code execution, you must return 'up the chain'. I just had to do this for an XML project. The return statement in the first controller method is what matters, so do a return in your redirect() method, then at that point in your next() method, and then return that redirect method in your index() method.

parker_codes
  • 3,267
  • 1
  • 19
  • 27
  • 1
    Ops, didn't know that this question already has an answer. :) – aceraven777 May 11 '18 at 02:30
  • @Laky remember that setting cookie via queue, might eventually break your next request. If you are on fast dev machine, all will probably be fine, and you won't even notice any problems, How about real life scenario? Especially if you want to scale and use multiple machines? – Bart May 11 '18 at 02:56
0

You to return the response in the main function. It's all about manipulating data / returning a response or view in your controller.

Please see, I updated your code:

class Example extends Controller{

    public function index(){

        Cookie::queue('examplecookie', 1, 525600);

        return $this->next();
    }


    public function next(){
        return $this->redirect();
    }


    public function redirect(){
        return redirect('http://someurl.com');
    }
}
aceraven777
  • 4,358
  • 3
  • 31
  • 55