我有一些像这样的代码:
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);
});
});
但是当我使用这样的公共变量时它不起作用:
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);
});
});
请帮帮我!
答案 0 :(得分:5)
当您使用Closure时,您需要显式授予对变量的访问权限,因为它们不在函数的上下文中。您可以使用"使用"功能
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);
});
});