samedi 24 décembre 2016

Access Auth in parent constructor in Laravel 5.3

Im working on an app in Laravel 5.3. I have created an AppController. I would like for all of my controllers to extend AppController so that they all share a few common properties and methods.

Given the below 2 implementations below, my intention is to set the current user to $this->user when AppController is constructed so it will be available to all controllers extending AppController.

I expect that when I call \App\Http\Controllers\User\PermissionController@test I should get my user object dumped twice. Once when AppController is initialized, and again when PermissionController@test is called.

However, inside of AppController __construct(), $this->user is always NULL while PermissionController@test dumps the user as expected.

AppController:

<?php

    namespace App\Http\Controllers\App;

    use App\Http\Controllers\Controller;

    class AppController extends Controller
    {
        /**
         * The current user when logged in
         * @var \User
         */
        protected $user;

        public function __construct()
        {
            if(\Auth::check() ) {
                $this->user = \Auth::user();
            }
            var_dump($this->user);
        }
    }

PermissionController:

<?php

    namespace App\Http\Controllers\User;

    use App\Http\Controllers\App\AppController;

    class PermissionController extends AppController
    {
        public function test()
        {
            if(\Auth::check() ) {
                // Do something
                $this->user = \Auth::user() ;
            }
            var_dump($this->user);
        } 
    }

If it matters, I'm using http://ift.tt/24YMb5y to auth against Active Directory.

Clearly I'm misunderstanding something hear. Why does AppController __construct() not dump the user?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire