我正在使用laravel 5.7,但无法在__construct()中获得当前用户ID。
我还尝试了Auth:id(),但它也无法正常工作。
如何在构造函数中获取当前用户ID?
use Illuminate\Support\Facades\Auth;
class TestController extends Controller
{
public $id;
public function __construct()
{
$this->middleware('auth');
$this->middleware(function ($request, $next) {
$this->id = Auth::user()->id;
return $next($request);
});
dd($this->id);
}
}
当前输出为空。
答案 0 :(得分:1)
返回后,您将不会转到下一条不会打印的语句。
如果要在视图中使用此视图,则无需通过视图,您可以像这样简单地访问已记录的用户ID
{{Auth->user->id}}
如果您想在控制器中使用它,请确保您已登录。
有时会话已过期,那么您将不会获得用户ID
use Illuminate\Support\Facades\Auth;
class TestController extends Controller
{
public $id;
public function __construct()
{
$this->middleware('auth');
$this->middleware(function ($request, $next) {
$this->id = Auth::user()->id;
dd($this->id);
return $next($request);
});
}
}
答案 1 :(得分:0)
You can only access the session in the closure. Just refactor your code to this:
public function __construct()
{
$this->middleware('auth');
$this->middleware(function ($request, $next) {
$this->id = Auth::user()->id;
dd($this->id);
return $next($request);
});
}
You can now use the value $this->id
in your controller methods.
In the example in your question, after you've set the value $this->id
, you continue with the request. Since you try to access $this->id
outside of the scope of the closure, it still is null
in the datadump.
答案 2 :(得分:0)
最简单的解决方案是创建一个中间件,然后在构造函数中调用它。
php artisan make:middleware FoobarMiddleware
我建议在Kernel.php中放置一个别名
protected $routeMiddleware = [
...
'foobar' => \App\Http\Middleware\FoobarMiddleware::class,
]
构造函数:
public function __construct()
{
$this->middleware('auth');
$this->middleware('foobar');
}
我建议更改创建所有内容的重点