Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

learn4u's avatar

Auth::user()->id not working in api.php

Hello ,

I have a question about the Auth::user()->id !

I want to use eloquent resource api for laravel .

I created this route :

Route::resource('tasks', 'API\TaskControllerAPI');

and I created a controller : TaskControllerAPI.php

my first function index() :

$tasks = Task::paginate(3) ; 
return TaskResources::collection($tasks) ;

It's workign fine .

I wanted to create an other function to store a list of tasks but I have a relation between the task table and the user table , a basic relation : user hasMany tasks .

I have a foreign key and I want to store the id_user in the tasks table .

so I used : Auth::user()->id ; and I imported 'use Auth' but I get this error 'trying to get a pro of non object' .

PS : I tested with web.php and it's working fine .

Thank you very much

0 likes
5 replies
hazemali's avatar

First rename the column to be user_id .. because it's the default when using relations if you want to change it you've to tell eloquent that inside the relationship method,

Second try to use Auth::id() direct or using Auth::check() before trying to get the id property from the User model ,, or using optional helper function to achieve the same behavior because when The user is not authenticated null will return from user method.

Good luck

D9705996's avatar

You might need to just use the correct import instead of use Auth

use Illuminate\Support\Facades\Auth;
learn4u's avatar

@hazemali , Thank you for your reply , I've changed the column name ! after the login I tested the web.php , it returns the user id but when I used the api.php it will give me that error , and I did a condition to check ( Auth::check() ) before getting the id but ot goes directly to the else it means I'am not loged in ? weird !

learn4u's avatar

@D9705996 , Thank you sir for your reply but I imported the full path but it doesn't work !

Snapey's avatar

Routes in api.php are stateless

You need to be passing an identity token with every request in order to be associated with a user account. Are you doing this or are you expecting it to be handled with sessions (as per web.php)

Please or to participate in this conversation.