它是不好的做法,我常常把我的基本控制器內的auth用戶如下:Laravel - 控制器構造函數中設置auth用戶
abstract class Controller extends BaseController
{
use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
protected $user;
public function __construct()
{
$this->middleware(function ($request, $next) {
$this->user = Auth::user();
view()->share('signedIn', Auth::check());
view()->share('user', $this->user);
return $next($request);
});
}
}
或者我應該訪問在我的控制方法auth用戶如下:
public function index()
{
$user = Auth::user();
}
我基於泰勒提出的意見(https://laravel-news.com/controller-construct-session-changes-in-laravel-5-3)
但是傑弗裏方式似乎在構造函數中爲數字高程模型要設置這個在Laracast的許多課程中演示過?
[在控制器的構造函數中調用一些中間件]非常普遍(https://laravel.com/docs/5.4/controllers#controller-middleware)。我會說傑弗瑞在那裏更快地展示了這個課程,在那裏設置了整個中間件代碼。去與文檔專用中間件,並在構造函數中調用它,你會沒事的。 – Tpojka
@Tpojka我知道在控制器的構造函數中調用中間件是很常見的,我的問題與解決在根據泰勒的構造函數中認證的用戶是不好的做法有關。 – adam78