2

whenever i tried to use \Auth::User() i am getting non object property because my Auth::guest() returns true whenever i use them in service provider

use Illuminate\Contracts\View\View;
use Illuminate\Support\ServiceProvider;
use Illuminate\Contracts\View\Factory;
use App\relations;
use App\User;
use DB;
use Illuminate\Support\Facades\Auth;

class RelationServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        //
        \Auth::User()->id;

        $relation_friend_for_logged_user = DB::select( DB::raw("SELECT * FROM users"));

        $value = "asd";

        // for injecting objct
        View()->share('count', $value);
    }

but why \Auth::guest() is returning true whether i am logged in

2
  • try to put your logic into if statement -- if(Auth::User()){ .. 'your logick'.. } Commented Aug 25, 2015 at 10:56
  • I am logged in whenever i tried using this Auth::user in my custom service provider which i registered is shows non object error when i tried to debug the auth::guest() seems to return true which means no user is logged in Commented Aug 25, 2015 at 10:59

1 Answer 1

10

You probably want to use a View Composer for this. As far as I know the authenticated user is not yet available in your service providers boot method.

public function boot(Guard $auth) {
    view()->composer('*', function($view) use ($auth) {
        // get the current user
        $currentUser = $auth->user();

        // do stuff with the current user
        // ...

        // pass the data to the view
        $view->with('currentUser', $currentUser);
    });
}

Code modified from https://laracasts.com/discuss/channels/general-discussion/how-do-i-get-the-current-authenticated-user-laravel-5

Sign up to request clarification or add additional context in comments.

1 Comment

I was wondering why this was not working, and want to add that something not too obvious is that for Laravel 5.1 you have to add to the top: use Illuminate\Contracts\Auth\Guard; or it won't work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.