Laravel 5.3:如何在全局中间件中使用 Check Auth?
Posted
技术标签:
【中文标题】Laravel 5.3:如何在全局中间件中使用 Check Auth?【英文标题】:Laravel 5.3 :How To use Check Auth in Global Middleware? 【发布时间】:2017-11-16 05:31:44 【问题描述】:我想在我的网站标题和其他一些视图中显示未读消息的数量。为此,我编写了一个全局中间件,但该中间件无法访问已注册用户的身份验证信息。
<?php
namespace PTA_OIMS\Http\Middleware;
use Illuminate\View\Factory;
use Closure;
use Illuminate\Contracts\Auth\Guard;
use PTA_OIMS\Kartable;
use Session;
class UnreadMessage
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
protected $auth;
protected $view;
public function __construct(Guard $auth, Factory $view)
$this->auth = $auth;
$this->view = $view;
public function handle($request, Closure $next)
$unreadMessage = NULL;
$user = $this->auth->check();
if (!empty($user))
$unreadMessage = Kartable::
where('id_reciver', '=',
Session::get('personnel_info.0')->box_id)
->whereBetween('status', [1, 2])
->where('view_date', '=', Null)
->count();
$this->view->share('unreadMessage', $unreadMessage);
return $next($request);
更新:
<?php
namespace PTA_OIMS\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
/**
* The application's global HTTP middleware stack.
*
* These middleware are run during every request to your application.
*
* @var array
*/
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
\PTA_OIMS\Http\Middleware\UnreadMessage::class,
];
/**
* The application's route middleware groups.
*
* @var array
*/
protected $middlewareGroups = [
'web' => [
\PTA_OIMS\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\PTA_OIMS\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
'api' => [
'throttle:60,1',
'bindings',
],
];
/**
* The application's route middleware.
*
* These middleware may be assigned to groups or used individually.
*
* @var array
*/
protected $routeMiddleware = [
'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \PTA_OIMS\Http\Middleware\RedirectIfAuthenticated::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
];
【问题讨论】:
从外观使用`\Auth` Auth::check() 返回一个布尔值,而不是用户实例,您希望在检查后使用 Auth::user() 获取用户。 这不属于中间件。中间件用于处理 HTTP 请求和响应。它更适合放在 view composer 中:laravel.com/docs/master/views#view-composers 【参考方案1】:尝试使用全局auth()
helper:
$user = auth()->check();
【讨论】:
@RohullahRajaeeRad 请显示app\Http\Kernel.php
你使用。以上是关于Laravel 5.3:如何在全局中间件中使用 Check Auth?的主要内容,如果未能解决你的问题,请参考以下文章
任何想法如何使用 vue js 和 vue 路由器在 laravel 5.3 中进行基于会话的身份验证