doushan2224 2018-01-28 22:13
浏览 13

饼干在Laravel不起作用?

When a new user visits my site I want to redirect them to /welcome but only once, I thought to do this I could use cookies and set a cookie forever once they had visited the welcome page and then checking if the cookie existed before sending them to /welcome.

Here I have a base controller

class BaseController extends Controller
{
    public function __construct(Request $request) 
    {
        $this->checkWelcome($request);
    }

    private function checkWelcome(Request $request) {
        $currentRoute = Route::currentRouteName();

        if ($currentRoute != 'frontend.guest.welcome' && Cookie::get('visited_welcome') != '1') {
            header('location: ' . route('frontend.guest.welcome'));
            exit();
        }
    }
}

When sending to frontend.guest.welcome it has a route to WelcomeController

Route::get('/welcome', ['uses' => 'WelcomeController@getView', 'as' => 'frontend.guest.welcome']);

Here is WelcomeController

class WelcomeController extends BaseController
{
    public function getView()
    {
        Cookie::forever('visited_welcome', '1');

        return view('frontend.guest.welcome');
    }
}

The issue is, its constantly sending to /welcome, not once but always.

  • 写回答

2条回答 默认 最新

  • duandu5846 2018-01-29 00:05
    关注

    You aren't returning the cookie with the response, attach it to the response like so:

    public function checkWelcome(Request $request) {
    {
        if (!$request->cookie('visited_welcome')) {
            return redirect('frontend.guest.welcome')->withCookie(Cookie::forever('visited_welcome', '1'));
        }
    
        // otherwise proceed as normal
    }
    

    Alternatively, you can use the queue method on the Cookie facade:

    Cookie::queue(Cookie::forever('visited_welcome', '1'));
    

    https://laravel.com/docs/5.5/responses#attaching-cookies-to-responses

    A better approach may be using middleware, that way you wouldn't need to implement any check in your controller code. For example:

    // CheckIfFirstTimeVisit.php
    public function handle(Request $request, Closure $next)
    {
        if ($request->cookies->has('visited_welcome')) {
            return $request($next);
        }
    
        return response()->view('frontend.guest.welcome')
                         ->withCookie(Cookie::forever('visited_welcome', '1'));
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?