首页 > 解决方案 > Laravel 在重定向之前保存 cookie

问题描述

我在重定向之前保存 cookie 时遇到问题,示例代码:

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');

    }
}

如果我在标头位置 PHP 停止后使用 die() 浏览器被重定向并且不保存 cookie,如果 die 不存在浏览器被重定向,cookie 被保存,但 PHP 仍然转到其他代码。此外,当使用 redirect() 时,会加载其他代码。例子:

public function redirect(){

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

}

这个类是一个逻辑示例,实际代码更复杂:)。我想保存 cookie、重定向并阻止 PHP 继续执行其他代码。

标签: phplaravelredirectcookies

解决方案


要返回结束代码执行的响应,您必须返回“上链”。我只需要为 XML 项目执行此操作。第一个控制器方法中的 return 语句很重要,所以在你的 redirect() 方法中返回,然后在你的 next() 方法中,然后在你的 index() 方法中返回那个重定向方法。


推荐阅读