Home > Software design >  get json response back from my PHP API in my laravel app
get json response back from my PHP API in my laravel app

Time:12-06

I'm sending data with Laravel HTTP client to a practice PHP API. my Laravel code:

        $p = 'img.jpg';

        $path = storage_path('app' . DIRECTORY_SEPARATOR . 'public' . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . $p);
        $response = Http::attach('new_file', file_get_contents($path), 'new_file.jpg')->post('http://localhost/imageresizer/service.php',
            ['sizes[0][new_width]' => 400, 'sizes[0][new_height]' => 200, 'sizes[1][new_width]' => 300, 'sizes[1][new_height]' => 500]);

        $json = json_decode($response);

        dd($json);

and i have this in my php scripts:

    $response = [
        'status' => http_response_code(),
        'zip name' => basename($zipname),
        'link' => 'http://localhost/imageresizer/zip/' . basename($zipname)
    ];
    header("Content-Type: application/json");
    echo json_encode($response);

I want to access each value from $response keys in my PHP API but i fail. How can i do it? (the current result for dd($json); is null). I want to do something like $json->$response['status']; in my Laravel app.

CodePudding user response:

try dd($response->json());.

CodePudding user response:

You have to use response() function to send back the requested data;

return response()->json(['data' => $dataToBeSent], 200);

You can use above code at end of that function. You can see full detail in this official document

  • Related