我使用Laravel 5.2并且中间件有问题。路线中有代码.php
使用照明''合同''身份验证''访问''门;路由::group(['中间件' => 'web'], 函数 (( { 路由::身份验证((; 路由::get('/', 'HomeController@index'(; });路由::group(['前缀'=>'admin', '中间件' => 'admin'], function(({ 路由::get('/', function(({ 返回视图('admin.index'(; }); 路由::get('/user', function(({ 返回视图('admin.user'(; }); });
内核.php:
受保护$routeMiddleware = [ ... 'admin' => ''App''Http''Middleware''AdminPanel::class, ];
管理面板.php
命名空间 App''Http''Middleware;使用闭包; 使用"照亮''支撑''立面''身份验证"; 使用应用''角色; 类管理面板 { 公共函数句柄($request、闭包$next( { $user = 身份验证::用户((; 日($user(; if($user({ $role = 角色::whereName('admin'(->first((; if($user->hasRole($role(({ 返回$next($request(; } } 返回重定向('/'(; }
所以,
$user = Auth::user
()
always return null.
Thanks for suggestions!I faced a situation where Auth::user()
always returns null
, it was because I was trying to get the User
in a controller's constructor.
I realized that you can't access the authenticated user in your controller's constructor because the middleware has not run yet.
As an alternative, you can define a Closure based middleware directly in your controller's constructor.
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);
});
}
}
任何使用 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');
});
});
});
在控制器的构造器中定义中间件,它将在这里解决问题
public function __construct()
{
$this->middleware('auth:api');
}
我遇到了同样的问题,因为我没有设置表名。
/**
* The table associated with the model.
*
* @var string
*/
protected $table = 'users';
我在旧代码中找到了一个解决方案
function getAuth($guard, $get)
{
return auth($guard)->user()->$get;
}
将此 ^ 添加为辅助函数,并在任何您想要的地方使用它前任:
getAuth('user', 'id');
你可以这样使用它。
$this->middleware(function ($request, $next) {
//Your Code Here
return $next($request);
});
它对我有用。
只需在调用中包含身份验证中间件
$user = auth('middleware')->user()
Route::middleware('auth:api')->group(function () {
Route::get('/details', 'UserController@details');
});
我的Auth::user()
在以下情况下返回null
- 我在数据库中没有用户表
- 我没有 id 字段作为表用户的主键