Auth::checker returns false even if the user is logged in

271 views Asked by At

First, I logged in and it gives off an error "Undefined $scholar" in my view.

if (Auth::check()) {
        $scholar = Scholar::where('user_id','=','Auth::User()->id')->count();
        view()->share('scholar', $scholar);
}

second,I tried to dd(Auth::check()); and it returned false while im logged in.
Why is Auth::check() returns false even if the user is logged in?

if (Auth::check()) {
    dd(Auth::check());
    $scholar = Scholar::where('user_id','=','Auth::User()->id')->count();
    view()->share('scholar', $scholar);
}
1

There are 1 answers

3
Latheesan On

Three mistakes:

  1. Your where clause is putting auth user id inside a quote, so it's evaluating it as a string hence the query is not finding any row

  2. You aren't exactly fetching a Scholar row, instead you are querying the count?

  3. You are accessing the authenticated user incorrectly

Try this:

if (Auth::check()) {
    $scholar = Scholar::where('user_id', '=', Auth::user()->id)->first();
    view()->share('scholar', $scholar);
}

P.S. Instead of Auth::user()->id you can also use Auth::id() - See more details here: https://laravel.com/docs/5.4/authentication