#Auth::id() returns NULL instead of the authenticated user's ID

16 messages · Page 1 of 1 (latest)

warped oxide
#

I have a SearchController for my Searchable models, in my case it looks like this

class SearchController extends Controller
{
   use Searchable;

   public function searchUsers(Request $request) {
       $query = $request->input('query');

       $users = User::search($query)
         ->get()
         ->except([Auth::id()])
         ->take(10);

//        \Log::info(Auth::id());

       return response()->json($users);
   }
}

When this piece of code runs, I get an error in my logs saying that the line with theexcept method throws and error of: Attempt to read property "id" on null {"exception":"[object] (ErrorException(code: 0): Attempt to read property \"id\" on null at C:\\Users... Logs also showed that Auth::id() returns null, but besides that I have no idea what is happening here. Any help is appreciated, thanks!

#

Forgot to mention, here is the toSearchableArray implementation for my User model: public function toSearchableArray(): array { return [ 'id' => $this->id, 'company_name' => $this->company_name, ]; }

#

I basically want to search by the company_name field of the User model, and exclude the logged in user from the final collection

#

ALSO forgot to mention that I am accessing the controller and the function through an api route

unique prawn
#

The most obvious cause would be that the route doesn't have the auth middleware. If you're using Sanctum, make sure that you haven't skipped a step in the installation guide, and make sure that your protected routes use the auth:sanctum middleware.

#

This could also be caused by misconfiguration in config/auth.php

#

And also, why are you adding the Searchable trait to a controller?

warped oxide
#

i wanted a dropdown menu to display all users that match the name the user is entering in real time, and searchable felt like what I was supposed to be using. chatgpt told me to make a searchcontroller for possible futur esearchable elements. maybe it wasnt the best choice though. I wouldnt know, havent slept for 20 hours

#

and i might have skipped the sanctum installation, my bad

rigid radish
#

chatgpt told me
🤦‍♂️

warped oxide
#

well I got it to work somewhat to my liking. pardon my smooth brain, but what would be the best way to approach what I'm trying to do?

rigid radish
#

Eloquent models shouldn’t know about “outside” stuff like requests, authentication, etc.

#

But as Mono2000 says, if you’re getting an error saying you’re trying to read id on null, then you’ve not authenticated a user.

warped oxide
#

and to fix it, I have to properly install and configure Sanctum. Correct?

#

And for the bootleg Algolia search, should I just stick with eloquent orm and let go of scout?

unique prawn