DEV Community

vimuth
vimuth

Posted on

Laravel JsonResource class and toArray method.

In Laravel, a JsonResource is part of Laravel's Eloquent API Resources that allows you to transform your Eloquent models (and model collections) into JSON format easily and consistently across your application. It provides a convenient way to control the exact structure of the JSON data you want to return for an API response.

toArray method

In Laravel's JsonResource, the toArray method plays a critical role by defining how the resource should be converted to an array, which is then automatically converted to JSON when the resource is returned from a route or controller.

Check this code

public function toArray(Request $request): array
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            "images" => json_decode($this->images),
        ];
    }
Enter fullscreen mode Exit fullscreen mode

Here this is the response of a model called Post. "posts" table has "images" column which stores json data

Image description

But PHP does not aware about json. It is just a string for PHP. So if we do like this,

return [
            'id' => $this->id,
            'name' => $this->name,
            "images" => $this->images,
        ];
Enter fullscreen mode Exit fullscreen mode

What they return in response will be a string.

Image description

But if we do like this, And *json_decode * the field

return [
            'id' => $this->id,
            'name' => $this->name,
            "images" => json_decode($this->images),
        ];
Enter fullscreen mode Exit fullscreen mode

json_decode will convert "$this->images" to a PHP array. And toArray method is all about converting PHP arrays to JSON arrays, and this will convert into an array,

Image description

See now it is already JSON array. Not a string. So you can use it straightaway inside loop from frontend without parsing.

Additional things

Json objects an arrays

In JSON (JavaScript Object Notation), {} and [] represent two fundamental data structures

{} denotes an object

{
  "name": "John Doe",
  "age": 30,
  "isStudent": false
}
Enter fullscreen mode Exit fullscreen mode

[] denotes an array

["apple", "banana", "cherry"]
Enter fullscreen mode Exit fullscreen mode

Arrays can also contain objects

[
  {"name": "John Doe", "age": 30},
  {"name": "Jane Doe", "age": 25}
]
Enter fullscreen mode Exit fullscreen mode

Convert string to json

"images": "["https://via.placeholder.com/640x480.png/0011bb?text=doloribus", "https://via.placeholder.com/640x480.png/00aa55?text=ab"]",
Enter fullscreen mode Exit fullscreen mode

This is a string that represents a JSON array of image URLs.

let imagesArray = JSON.parse(imagesString);
Enter fullscreen mode Exit fullscreen mode

This will convert it to json array and you can loop through that array.

Top comments (0)