Pembina semakan pengesahan Laravel 5.3 mengembalikan palsu
P粉769045426
P粉769045426 2023-10-24 20:03:40
0
2
598

Saya menggunakan Laravel 5.3 并且我试图在 constructor 方法中获取经过身份验证用户的 id supaya saya boleh menapis pengguna mengikut syarikat tertentu seperti ini:

namespace AppHttpControllers;

use IlluminateFoundationBusDispatchesJobs;
use IlluminateRoutingController as BaseController;
use IlluminateFoundationValidationValidatesRequests;
use IlluminateFoundationAuthAccessAuthorizesRequests;
use IlluminateSupportFacadesView;
use AppModelsUser;
use AppModelsCompany;
use IlluminateSupportFacadesAuth;


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);
        }

    }

Tetapi ini tidak mengembalikan pengguna id。我什至尝试过 Auth::check()Tetapi ia tidak berfungsi.

Jika saya menambah kaedah Auth::check() 移出 __construct(), ia berfungsi seperti ini:

<?php

namespace AppHttpControllers;

use IlluminateHttpRequest;

class HomeController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
        $this->middleware('auth');
    }

    /**
     * Show the application dashboard.
     *
     * @return IlluminateHttpResponse
     */
    public function index()
    {
        dd(Auth::check());
        return view('home');
    }
}

Tetapi jika saya juga memasukkannya ke dalam pembina HomeController, ini gagal!

Ada idea mengapa ini gagal?

P粉769045426
P粉769045426

membalas semua(2)
P粉277464743

Setakat 5.3 Auth::check ia tidak akan berfungsi dalam pembina pengawal, ini adalah salah satu perubahan tanpa dokumen. Jadi anda perlu mengalihkannya ke perisian tengah atau semak kaedah pengawal, atau alihkan projek anda ke 5.2.x.

P粉489081732

Dokumentasi

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);
        });
    }
}
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan