Laravel 5.3 auth check in构造函数返回false

时间:2016-08-27 22:10:48

标签: php laravel authentication laravel-5.3

我正在使用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()移出__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');
    }
}

然而,如果我把它放在HomeController的构造方法中,那么会失败

为什么会失败的任何想法?

3 个答案:

答案 0 :(得分:9)

docs

  

您无法访问您的会话或经过身份验证的用户   控制器的构造函数,因为中间件还没有运行。

     

作为替代方案,您可以直接定义基于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);
        });
    }
}

答案 1 :(得分:8)

由于5.3 Auth::check不能在控制器的构造中工作,因此它是未记录的变更之一。因此,您需要将其移至中间件或改为检入控制器方法,或将项目移至5.2.x。

答案 2 :(得分:2)

失败是因为您在$this->middleware('auth');之后致电parent::__construct();。这意味着你没有正确加载auth中间件。