duanjiong2021 2017-05-18 14:52
浏览 49

在Laravel 5.4中设置会话变量

I have a feeling this is a very dumb question and there's probably something really tiny I just overlooked, but I'm stumped anyway.

Currently, I have an app with a few pages that are protected through middleware. If the user does not meet the requirements of these middleware, they are redirected to a login page. Now after they log in, I want them to be sent back to the page they tried to visit.

I've tried numerous things to accomplish this, but none work. What I'm trying to do now is the following:

  1. User attempts to access an admin page (for example /admin): PagesController@adminDashboard
  2. When they access the overview() method in the controller (same as index(), but for admins), a session variable is set containing the url they tried to visit (/admin)
  3. The user is redirected to the login page and logs in (SessionsController@create and @store)
  4. After logging in, they are redirected to the session variable with the intended URL

This is how I tried to do it:


PagesController

public function adminDashboard()
{
    $intended = '/admin';
    session('intended-url', $intended);

    //dd(session('intended-url');

    $schools = School::all();
    $articles = Article::all();
    $sights = Sight::all();

    return view('admin', compact('sights', 'articles', 'schools'));
}

SessionsController

public function store()
{
    /*
        ...
    */

    $intendedURL = session('intended-url');

    if($intendedURL != null)
    {
        return redirect($intendedURL);
    }
    else
    {
        return redirect()->home();
    }

Using dd() a few times here and there, I found out that it doesn't even set the session variable at the very start (commented dd() in PagesController returns null).

I've tried doing this using Session::put(), Session::set(), using square brackets as in session(['intended-url', '/admin']), but none of it gives me the result I'm looking for :(

Does anyone have any advice on how to do this, or perhaps a different way of accomplishing the same goal, but more efficiently? Thank you!

EDIT: I don't think the default Laravel redirect to intended page will work here, since I rewrote most of the login system from scratch to suit some specific needs. Unless anyone knows how that redirect works behind the scenes and I can over-/rewrite it

  • 写回答

2条回答 默认 最新

  • dongqi8114 2017-05-18 15:04
    关注

    If you are using the default auth system, you can use this to redirect users to the page they wanted to view:

    return redirect()->intended('fallback/uri');
    
    评论

报告相同问题?

悬赏问题

  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥50 我撰写的python爬虫爬不了 要爬的网址有反爬机制
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥120 计算机网络的新校区组网设计
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等