334 words, 2 min read

If you want to do multiple HTTP requests in a row using the HTTP client from Laravel and persist cookies between them, you can use a cookie jar. This is a class that stores cookies and sends them back to the server when needed. Here's how you can use it:

use GuzzleHttp\Cookie\CookieJar;
use Illuminate\Support\Facades\Http;
// Create a cookie jar to store cookies
$cookieJar = new CookieJar();
// Create a new HTTP client with the cookie jar
// You can also set other options here, like the base URL or whether to follow redirects
$client = Http::baseUrl('https://www.mywebsite.com')
->withOptions(['cookies' => $cookieJar])
->withoutRedirecting()
->throw();
// Make a request that sets a cookie (e.g., logging in)
$authResp = $client->asForm()->post(
url: '/login',
data: [
'username' => 'username',
'password' => 'password',
]
);
// Store the cookies from the response in the cookie jar
$cookies = $authResp->cookies();
foreach ($cookies as $cookie) {
$cookieJar->setCookie($cookie);
}
// Make another request that requires authentication (which relies on the cookies being present)
$authenticatedResponse = $client->get('/authenticated-page');

If you want to do the same in Golang, you can do this:

package main
import (
"bytes"
"fmt"
"net/http"
"net/http/cookiejar"
"net/url"
)
func main() {
// Create a cookie jar to store cookies
cookieJar, _ := cookiejar.New(nil)
// Create a new HTTP client with the cookie jar
client := &http.Client{
Jar: cookieJar, // Use this cookie jar
CheckRedirect: func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse // Don't follow redirects
},
}
// Create a request body with the login credentials
params := url.Values{}
params.Set("username", "username")
params.Set("password", "password")
body := bytes.NewBufferString(params.Encode())
// Make a request that sets a cookie (e.g., logging in)
// The response cookies will automatically be stored in the cookie jar
authReq, _ := http.NewRequest(http.MethodPost, "https://www.mywebsite.com/login", body)
_, _ = client.Do(authReq)
// Make another request that requires authentication (which relies on the cookies being present)
authenticatedReq, _ := http.NewRequest(http.MethodGet, "https://www.mywebsite.com/authenticated-page", nil)
authenticatedResp, _ := client.Do(authenticatedReq)
defer authenticatedResp.Body.Close()
// Print the response status and headers
fmt.Println("response Status : ", authenticatedResp.Status)
fmt.Println("response Headers : ", authenticatedResp.Header)
}