问题描述
我正在尝试检查输入的URL是否与数据库中已通过身份验证的用户所输入的URL相同.因此,如果用户转到example.com/user/bob-smith并且实际上是Bob Smith登录的,则该应用程序将让Bob继续,因为他在User表中的子弹头是bob-smith.
I'm trying to check if the URL entered is the same as the authenticated users slug in the database. So if a user goes to example.com/user/bob-smith and it is in fact Bob Smith logged in, the application will let Bob continue because his slug in the User table is bob-smith.
我已经注册了中间件,但是在注册时
I have the middleware registered but when I do
public function handle($request, Closure $next)
{
if($id != Auth::user()->slug){
return 'This is not your page';
}
else{
return $next($request);
}
}
我知道
我不确定如何在中间件内部使用它.可以帮忙吗?
I'm not sure how to use this inside of middleware. Can any one help?
推荐答案
这很容易.看来您没有导入Auth
门面的名称空间.
It's quite easy. It looks like you didn't import the namespace for Auth
facade.
因此要么添加
<?php namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth; // <- import the namespace
class YourMiddleware {
...
}
在类声明上方或使用完全限定的类名内联
above the class declaration or use a fully qualified class name inline
if ($id != \Illuminate\Support\Facades\Auth::user()->slug) {
或者,您可以在构造函数中注入Guard
实例
<?php namespace App\Http\Middleware;
use Closure;
use Illuminate\Contracts\Auth\Guard;
class YourMiddleware {
protected $auth;
public function __construct(Guard $auth)
{
$this->auth = $auth;
}
public function handle($request, Closure $next)
{
...
if ($id != $this->auth->user()->slug) {
...
}
}
这篇关于在中间件中使用Auth :: user的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!