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

mercury131's avatar

How to login via cookie to Laravel API

Hello everyone!

I have simple API login endpoint, this looks like this method in login controller:

public function login(Request $request)
{
    $this->validateLogin($request);

    if ($this->attemptLogin($request)) {
        $user = $this->guard()->user();

        return response()->json([
            'data' => $user->toArray(),
        ]);
    }

    return $this->sendFailedLoginResponse($request);
}

With this simple route in /routes/api.php

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

And this works fine, I can login to API via CURL command like this:

curl -X POST localhost/api/login -H "Accept: application/json" -H "Content-type: application/json" -d "{\"email\": \"test3@test3.local\", \"password\": \"test123\" }" After this post request i get my user data in JSON format.

But I want use cookie to next login to my API, without enter login and password in every post request.

I think I can do it with CURL -b parameter to save session cookie and use it saved cookie with CURL -c parameter to next login to API

But when I try run curl -X POST localhost/api/login -H "Accept: application/json" -H "Content-type: application/json" -d "{\"email\": \"test3@test3.local\", \"password\": \"test123\" }" -b my_cookie

I can't get and save cookie and I don't have my_cookie file on my local filesystem.

How I must change my controller?

Where is my mistake?

Thanks in advance!

0 likes
3 replies
RamjithAp's avatar
Level 10

Use Laravel builtin API package passport which will do all these things by default. Check https://laravel.com/docs/5.5/passport once you have passport installed, you can do below logic

getDataFromApi($url){
  if($_COOKIE['token']){
  //cuRL request to your API end point with token
  } else {
  //cuRl request to your login end point to get new token
  //then save the token in your local storage as cookie
  setcookie('token', $token, time() + (86400 * 30), "/"); 
  //cuRL request to your API end point with token
  }
return $results;
}
shez1983's avatar

cookie with an api? you can use passport but i am not convinced if it works with cookies.. you might need to store the authe token in your cookie which u send to the api url as header.. but thats a diff thing,

mercury131's avatar

Thank you! I will try to use passport package.

Please or to participate in this conversation.