mercredi 1 juin 2016

What is the better way to set Auth::user() object in Laravel controller's constructor

Laravel's Php Artisan Route:list will throw exception when we instantiate Auth::user() in controller constructor

When you run php artisan route:list, Laravel instantiates all controllers to check, if they declare a middleware - it's usually done in constructor by a call to middleware() method. At this point, there is no user session, therefore Auth::user() won't return anything, and we will getting an error trying to access name property on non-object.

Example:

     class settingController extends Controller
    {
        protected $user;

        public function __construct(ImageRepo $image)
        {
            $this->user =  Auth::user();
            $this->image = $image;
        }
......

Exception

C:\laragon\www\water2>php artisan route:list -v


  [Symfony\Component\Debug\Exception\FatalErrorException]                                                     
  Cannot use Illuminate\Contracts\Auth\Authenticatable as Authenticatable because the name is already in use  

What is the better way to store User Object?

Reference

I get the error in php artisan route:list command in laravel?

@jedrzej.kurylo You shouldn't access user object in the constructor, do that in action methods.

But how?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire