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

angelorigo's avatar

Json format transform from object to array

Hi, i have a Json returning into object format, is there a Laravel method to turn the object into an array ?

In short i need to transform from : { "data": { ... } ( is the result from this query : $myValue = MyModel::myProperty($this->myProperty)->where('typo','=',"myType")->first(); )

To :

{ "data": [ ... ] ( is the result from this query : $myValue = MyModel::myProperty($this->myProperty)->find($id); )

1 like
7 replies
LaryAI's avatar
Level 58

To transform a JSON object into an array in Laravel, you can use the toArray() method provided by Eloquent models. This method converts the model instance into an array, which can then be encoded into JSON if needed.

Here's how you can achieve this transformation:

  1. Retrieve the Object: First, retrieve your object using Eloquent. For example, using the first() method.

  2. Convert to Array: Use the toArray() method to convert the object to an array.

  3. Wrap in a JSON Array: If you need the data to be specifically wrapped in a JSON array, you can manually wrap it.

Here's a code example:

// Retrieve the object
$myValue = MyModel::myProperty($this->myProperty)
    ->where('typo', '=', "myType")
    ->first();

// Convert the object to an array
$arrayData = $myValue ? $myValue->toArray() : [];

// Wrap the data in a JSON array format
$jsonData = json_encode(['data' => [$arrayData]]);

// Output or return the JSON data
echo $jsonData;

In this example:

  • We first retrieve the object using Eloquent's first() method.
  • We then convert the object to an array using toArray().
  • Finally, we wrap this array in another array to match the desired JSON format and encode it using json_encode().

This will give you a JSON structure where the data key contains an array, even if it only has one element.

angelorigo's avatar

@LaryAI i try but gives me the message: "Call to a member function toArray() on string",

JussiMannisto's avatar

@angelorigo The error message tells you what's wrong. You're tring to call toArray() on a string instead of a model. Lary's example uses a model, which wouldn't give that error.

If you need to convert a JSON string into an array, use json_decode() like @vincent15000 said.

1 like
angelorigo's avatar

Hi! @vincent15000 The toArray() Method from : vendor\laravel\framework\src\Illuminate\Http\Resources\Json\JsonResource.php:120

1 like

Please or to participate in this conversation.