Beginner
Beginner

Reputation: 1740

Auth::id() returns null laravel

i have a function where

public function index(){
   $users = User::doesntHave('roles')->latest()->paginate()->except(Auth::id());
   return UsersResource::collection($users);
}

when i dd the Auth::id() it returns null even if I declared the auth facade on my controller

use Illuminate\Support\Facades\Auth;

this is my route which is stored inside api.php

Route::resource('users','Users\AdminUsersController')->except([
    'create', 'edit'
]);

Upvotes: 5

Views: 8073

Answers (3)

rkj
rkj

Reputation: 8287

Add your auth protected routes inside auth:api middleware

Route::post('login','LoginController@login');

Route::middleware(['auth:api'])->group(function () {

    Route::resource('users','Users\AdminUsersController')->except([
    'create', 'edit'
    ]);

    //other authenticated Routes goes inside this block

}); 

For Api authentication i suggest you to look https://laravel.com/docs/5.6/passport

Upvotes: 3

J Ajith
J Ajith

Reputation: 1

$users = User::doesntHave('roles')->latest()->paginate()->except(Auth::user()->id);

Upvotes: 0

Asheeka K P
Asheeka K P

Reputation: 417

Are you're signed in. It doesn't sound like it.

Don't use Illuminate\Support\Facades\Auth; instead it is just use Auth;.

You can do the following:

auth()->check(); // this checks to see if you're logged in

$userId = auth()->check() ? auth()->id() : null;

auth()->id(); // this is the same as Auth::id();

auth()->user();

Upvotes: 0

Related Questions