Laravel - Auth::user() 在__construct中失效 Auth::user() is not working in constructor
Laravel 原本在
__construct
中是可以直接調用Auth::user()
去取得使用者的,但是在Laravel 5.3 之後的版本,無法在
__construct
中取用session variables與authenticated user ,因為這個時候middleware
還沒有執行。如果需要在
__construct
中使用,我們可以直接在Controller
裡的constructor
使用基於middleware
的Closure
:
<?php namespace App\Http\Controllers;
use App\User;
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\Controller;
class ProjectController extends Controller {
/*** All of the current user's projects. */
protected $projects;
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct() {
$this->middleware(function ($request, $next) {
$this->projects = Auth::user()->projects;
return $next($request);
});
}
}
當然也可以不寫在constructor裡,直接寫在function裡
/**
* Show all of the projects for the current user.
*
* @param \Illuminate\Http\Request $request
* @return Response
*/
public function index(Request $request)
{
$projects = $request->user()->projects;
$value = $request->session()->get('key');
//
}
在使用這些特些之前必須確認Laravel的版本是在5.3.4或以上
留言
張貼留言