iml*_*ris 18 php authentication middleware laravel-5
我使用Laravel 5.2并且遇到中间件问题.routes.php中有代码
use Illuminate\Contracts\Auth\Access\Gate;
Route::group(['middleware' => 'web'], function () {
Route::auth();
Route::get('/', 'HomeController@index');
});
Route::group(['prefix'=>'admin', 'middleware' => 'admin'], function(){
Route::get('/', function(){
return view('admin.index');
});
Route::get('/user', function(){
return view('admin.user');
});
});
Kernel.php:
protected $routeMiddleware = [
...
'admin' => \App\Http\Middleware\AdminPanel::class,
];
AdminPanel.php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
use App\Role;
class AdminPanel
{
public function handle($request, Closure $next)
{
$user = Auth::user();
dd($user);
if($user){
$role = Role::whereName('admin')->first();
if($user->hasRole($role)){
return $next($request);
}
}
return redirect('/');
}
所以,
$user = Auth::user()总是返回null.谢谢你的建议!
Hem*_*ela 36
我遇到了Auth::user()总是返回的情况null,这是因为我试图获得User控制器的构造函数.
我意识到您无法访问控制器构造函数中的经过身份验证的用户,因为中间件尚未运行.
作为替代方案,您可以直接在控制器的构造函数中定义基于Closure的中间件.
namespace App\Http\Controllers;
use App\User;
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\Controller;
class ProjectController extends Controller
{
protected $user;
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware(function ($request, $next) {
$this->user = Auth::user();
return $next($request);
});
}
}
Run Code Online (Sandbox Code Playgroud)
cam*_*ase 30
任何使用的路由都Auth()必须封装在web中间件中.你很亲密,只需要Route::group(['prefix' => 'admin'], ...)进入上面的小组.
Route::group(['middleware' => 'web'], function () {
Route::auth();
Route::get('/', 'HomeController@index');
// Moving here will ensure that sessions, csrf, etc. is included in all these routes
Route::group(['prefix'=>'admin', 'middleware' => 'admin'], function(){
Route::get('/', function(){
return view('admin.index');
});
Route::get('/user', function(){
return view('admin.user');
});
});
});
Run Code Online (Sandbox Code Playgroud)