Daniel-Pablo's avatar

opinion and feedback about calling a $user...

Hi, laracast community I have been thinking about what's the best way to call a User in laravel projects, I think that there is no app if there is no USER , because you have the landing page where all are GUEST, But when we are really into the THING there must be a user, so my thoughts are that in all VIEWS and CONTROLLERS must be the instance of the USER , so in the app service provider I create this:

    public function boot()
    {
        View::composer( [ 'pages.*' ] , UserComposer::class );
    }

//// on UserComposer class got thiss

$view->with( 'user', Auth::user() );

So... now I can access all the pages to the instance $user, I want to have this instance in my controllers to... but I don't know how to do it, now I ask my self... This is the right way to do it? , I mean should I call this instance in the controllers too, and can be called in the MODELS?

I end up with this because I see that I have to call this Auth::user() in all the controller's methods and then in the view blade the same thing, so I want to know how do you manage this? whats the best way to affront this.

Very grateful to count with this excellent laracast forum community Thanks in advance for your feedback

Regards Santino

0 likes
5 replies
MichalOravec's avatar

You don't need nothing more

In controller

Auth::user();

// or

$request->user();

// or

auth()->user();

In view

@if (auth->check())
    {{ auth()->user()->email }}
@endif
1 like
Daniel-Pablo's avatar

@michaloravec , Hi Michael, yes I haad been using the Auth::User() but don't you feel that is too much large to type it every time ... don't you feel its better to call

$user.......
$user->account
$user->profile
$user->wallet()

BUT - all this above dont have to been called before, just on the appProvider

I think it is faster to do it with the View facade, or what do you think?

MichalOravec's avatar
Level 75

If it's too much for you then create your custom helper

if (! function_exists('user')) {
    function user()
    {
        return auth()->user();
    }
}

Then instead of auth()->user() you can just use user()

user()->account

user()->profile

// and so on

But it's basically same thing.

But really don't do that what you posted in the top of this thread.

Daniel-Pablo's avatar

Just do the helper, like it, because you can call this inside the controller, I can't do it with the View facade, thanks!!

Please or to participate in this conversation.