douyanqu9722 2016-05-28 09:56
浏览 57
已采纳

Laravel 5 Route ::具有公共变量的组

I have some code like this:

Route::group(['prefix'=>'dashboard'],function(){        
    Route::get('addnew',function(){
        $user = DB::table('users')->where('username','=',session('username'))->first();
        $data = array('level' => $user->level, 'name' => $user->name,'email' => $user->email);
        return view('layout.addnew')->with($data);
    });
    Route::get('load',function(){
        $user = DB::table('users')->where('username','=',session('username'))->first();
        $data = array('level' => $user->level, 'name' => $user->name,'email' => $user->email);
        return view('layout.load')->with($data);
    });
});

But it don't work when i use public variable like this:

Route::group(['prefix'=>'dashboard'],function(){

    $user = DB::table('users')->where('username','=',session('username'))->first();
    $data = array('level' => $user->level, 'name' => $user->name,'email' => $user->email);

    Route::get('addnew',function(){        
        return view('layout.addnew')->with($data);
    });
    Route::get('load',function(){        
        return view('layout.load')->with($data);
    });
});

Help me please!

  • 写回答

1条回答 默认 最新

  • doutao6330 2016-05-28 11:35
    关注

    As you're using a Closure, you need to explicitly grant access to the variables, as they are outside of the context of the function. You do this with the "use" function.

    Route::group(['prefix'=>'dashboard'],function(){
    
        $user = DB::table('users')->where('username','=',session('username'))->first();
        $data = array('level' => $user->level, 'name' => $user->name,'email' => $user->email);
    
        Route::get('addnew',function() use($data) {        
            return view('layout.addnew')->with($data);
        });
        Route::get('load',function() use($data) {        
            return view('layout.load')->with($data);
        });
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 关于#html5#的问题:H5页面用户手机返回的时候跳转到指定页面例如(语言-javascript)
  • ¥15 无法使用此凭据登录,因为你的域不可用,如何解决?(标签-Windows)
  • ¥15 yolov9的训练时间
  • ¥15 二叉树遍历没有报错但无法正常运行
  • ¥15 在linux系统下vscode运行robocup3d上场球员报错
  • ¥15 Python语言实验
  • ¥15 SAP HANA SQL 增加合计行
  • ¥20 用C#语言解决一个英文打字练习器,有偿
  • ¥15 srs-sip外部服务 webrtc支持H265格式
  • ¥15 在使用abaqus软件中,继承到assembly里的surfaces怎么使用python批量调动