我正在使用,Laravel 5.3并且尝试在方法中获取经过 身份验证的 用户id,constructor因此可以按分配的公司过滤用户,如下所示:
Laravel 5.3
id
constructor
namespace App\Http\Controllers; use Illuminate\Foundation\Bus\DispatchesJobs; use Illuminate\Routing\Controller as BaseController; use Illuminate\Foundation\Validation\ValidatesRequests; use Illuminate\Foundation\Auth\Access\AuthorizesRequests; use Illuminate\Support\Facades\View; use App\Models\User; use App\Models\Company; use Illuminate\Support\Facades\Auth; class Controller extends BaseController { use AuthorizesRequests, DispatchesJobs, ValidatesRequests ; public $user; public $company; public function __construct() { $companies = Company::pluck('name', 'id'); $companies->prepend('Please select'); view()->share('companies', $companies); $this->user = User::with('profile')->where('id', \Auth::id())->first(); if(isset($this->user->company_id)){ $this->company = Company::find($this->user->company_id); if (!isset($this->company)) { $this->company = new Company(); } view()->share('company', $this->company); view()->share('user', $this->user); } }
但是,这不会返回用户id。我什至尝试过Auth::check(),但不起作用。
Auth::check()
如果我移动Auth::check()了的__construct()方法,那么这种工作方式如下:
__construct()
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; class HomeController extends Controller { /** * Create a new controller instance. * * @return void */ public function __construct() { parent::__construct(); $this->middleware('auth'); } /** * Show the application dashboard. * * @return \Illuminate\Http\Response */ public function index() { dd(\Auth::check()); return view('home'); } }
但是,如果我也把它放在construct方法中,这将 失败HomeController!
HomeController
有什么想法为什么会失败吗?
docs
您无法在控制器的构造函数中访问会话或经过身份验证的用户,因为中间件尚未运行。 或者,您可以直接在控制器的构造函数中定义基于Closure的中间件。使用此功能之前,请确保您的应用程序正在运行Laravel 5.3.4或更高版本:
您无法在控制器的构造函数中访问会话或经过身份验证的用户,因为中间件尚未运行。
或者,您可以直接在控制器的构造函数中定义基于Closure的中间件。使用此功能之前,请确保您的应用程序正在运行Laravel 5.3.4或更高版本:
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); }); } }