OneBite.Dev - Coding blog in a bite size

Get value response json from other funtion in Laravel

Here is how in Laravel if you need to get the value of response that returned json from local function

In order to read the data from another function that return a response JSON in Laravel, we should use getData() function, then encode and decode the value.

If you try to access it directly, probably you’ll get an error

Cannot use object of type jsonresponse as array

Simple Sample

$response = $this->anotherFunction();
$data = json_decode(json_encode($response->getData()), true);

Now you can use the data

if ($data['success']) 

Sample Code

class YourController extends Controller
{
    public function yourFunction()
    {
        $response = $this->anotherFunction();

        $data = json_decode(json_encode($response->getData()), true);

        if ($data['success']) {
            $content = $data['data']['content'];
            // Do something with $content
        }
    }

    public function anotherFunction()
    {
        $content = 'Your content';

        return response()->json([
            'success' => true,
            'data' => [
                'content' => $content
            ]
        ]);
    }
}
laravel