For Auth::user(), the user information is kept in the session.
When you are doing a curl, there is no session. So Auth::user() is null
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
Hello, I am really stuck on this weird thing. I made API calls, routes etc, and it all works fine when I test it in browser. For example this
http://appsforce.back/api/v1/100000001/env
Returns
{"code":200,"message":"Request was succesfull","data":{"host":"127.0.0.1","dbuser":"root","dbpassword":"","dbprefix":"back_"}}
While:
$url = $_SERVER['HTTP_HOST'] .'/api/v1/100000002/env';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HTTPGET, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response_json = curl_exec($ch);
curl_close($ch);
$response=json_decode($response_json, true);
Returns same result. So far is so good if I don't use in my code call to Auth::user();
So this is the code that returns result:
$user = \Auth::user();
$env = array(
'host' => $_ENV['DB_HOST'],
'dbuser' => $_ENV['DB_USERNAME'],
'dbpassword' => $_ENV['DB_PASSWORD'],
'dbprefix' => $_ENV['DB_PREFIX']);
$response = array(
'code' => 200,
'message' => $this->codes['200'],
'data' => $user,
);
return $response;
If I put 'data' =>$user this returns NULL, while 'data' => $env returns correct $_ENV settings when called via cURL.
For my APIs I need to use \Auth::user() and I just cannot get it to work through cURL while HTTP calls in browser work just fine and the user is returned:
{"code":200,"message":"Request was succesfull","data":{"id":10,"username":"afabris","firstname":"Andre","lastname": .....
many thanks, Andre
Are these external applications on the same domain as the Laravel application the user is logging into? If not then they will not have the same cookies and thus cannot share session data.
Assuming the applications do share cookies you would have to add the current session cookie to the request.
The name of the cookie is defined in the session.php config file and defaults to laravel_session.
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Cookie: laravel_session={$_COOKIE['laravel_session']}"));
Please or to participate in this conversation.