【问题标题】:Is it possible to setCookie() in Laravel 5 before returning from the controller method?从控制器方法返回之前,是否可以在 Laravel 5 中设置 Cookie()?
【发布时间】:2015-09-03 06:39:09
【问题描述】:

我在控制器方法中有一些示例代码,用于查找 cookie 并在模型存在时对其进行操作,或者创建新模型并在不存在时返回新 cookie。

是否可以在我返回视图之前添加cookie,这样重复的代码只能写一次?

我只是追求效率和整洁。

$cat = Cat::find($request->cookie('cat_id'));
if (null !== $cat) {
    if ($cat->name === 'Felix') {
        $cat->age = 10;
    } else {
        $cat->age = 8;
    }

    //duplicated code
    $cat->fur = 'soft';
    $cat->tail = 'wavy';
    $cat->save();

    return redirect('/');

} else {
    $cat = new Cat;
    $cat->name = 'Ralf';
    $cat->age = 12;

    //duplicated code
    $cat->fur = 'soft';
    $cat->tail = 'wavy';
    $cat->save();

    return redirect('/')->withCookie(cookie('cat_id', $cat->id,10000));
}

【问题讨论】:

  • 使用服务提供商。

标签: php laravel cookies laravel-5


【解决方案1】:

redirect() 方法在将字符串传递给它时返回 Illuminate\Http\RedirectResponse,Laravel 路由堆栈将其解释为发送特定响应头的方向。因此,您可以这样做,而不是返回两次:

$cat = Cat::find($request->cookie('cat_id'));
$redirect = redirect('/');

if (null !== $cat) {
    if ($cat->name === 'Felix') {
        $cat->age = 10;
    } else {
        $cat->age = 8;
    }

    //duplicated code
    $cat->fur = 'soft';
    $cat->tail = 'wavy';
    $cat->save();
} else {
    $cat = new Cat;
    $cat->name = 'Ralf';
    $cat->age = 12;

    //duplicated code
    $cat->fur = 'soft';
    $cat->tail = 'wavy';
    $cat->save();

    $redirect->withCookie(cookie('cat_id', $cat->id,10000));
}

return $redirect;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-08-16
    • 2015-06-14
    • 2021-06-25
    • 1970-01-01
    • 2015-10-09
    • 1970-01-01
    • 2011-09-06
    • 2016-11-18
    相关资源
    最近更新 更多