0
votes

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?

1
dont use the facade , inject the Auth contract (namespace\Auth $auth) then $this->user = $auth;Achraf Khouadja

1 Answers

1
votes

You can definitely do:

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

If no user is authenticated you will have $this->user equal to null.

In your view file you can simply check:

@if($user)
   <h1>Hello, {{ $user->name }}</h1>
@endif

The error you are getting seems to be related to some use statement trying to re-declare Authenticatable

Check your User model and Controllers for duplcation of this line:

use Illuminate\Contracts\Auth\Authenticatable as Authenticatable