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

thebham's avatar

Guzzle Relay to Another Laravel API

I have a main api middleware that relays an incoming request to another laravel based api.

the receiving api is unable to validate as the $request->input() doesnt have the json data in the correct place. it thinks 'data' is a field instead of the json data for the request.

when i call return response($request->all()) on a bad request it looks like

"data":"{"field_name":"example_data"}"

when a successful request should look like

{"field_name":"example_data"}

so that if i validate $request->field_name it works.

if i post directly to the receiving api everythinglooks right so i just dont understand why this relay with guzzle isnt working.

public function handle($request, Closure $next)
    {
            $client = new Client(['base_uri' => 'https://api.api', 'verify' => false]);
            $multipart = [];
            if($request->hasFile('file')){
                $multipart = [
                    [
                        'name'     => 'file',
                        'contents' => fopen($request->file->path(), 'r'),
                        'filename' => $request->file->getClientOriginalName(),
                    ]
                ];
            }

            $data = [
                'name'     => 'data',
                'contents' => json_encode($request->all()),
            ];

            array_push($multipart, $data);

                       $response = $client->request($request->method(), 'https://api.api/', ['headers' => ['Accept' => 'application/json', 'Authorization' => 'Bearer ' . $request->bearerToken()], 'timeout' => 60, 'multipart' => $multipart]);
            $body = $response->getBody();
            $content = $body->getContents();

            return response($content);
    }

thank you for all your help.

0 likes
2 replies
thebham's avatar

on my receiving api route I just did $request->replace(json_decode($request->data, true));

and continued with the route and everything worked as expected.

i really dont want to add another middle ware that handles this. i feel like i should be able to send the request via the relay middle ware in the correct format that the receiving laravel api excepts its standard.

thebham's avatar

ok so what i decided to do was detect if i have a file and relay as multipart, otherwise i just relay everything else as form_params.

seems to be working for our use case right now.

Please or to participate in this conversation.