{"id":8146,"date":"2023-06-21T10:20:52","date_gmt":"2023-06-21T10:20:52","guid":{"rendered":"https:\/\/www.bacancytechnology.com\/qanda\/?p=8146"},"modified":"2023-08-07T05:30:24","modified_gmt":"2023-08-07T05:30:24","slug":"recursive-to-array-for-laravel","status":"publish","type":"post","link":"https:\/\/www.bacancytechnology.com\/qanda\/laravel\/recursive-to-array-for-laravel","title":{"rendered":"Recursive ->toArray() for Laravel"},"content":{"rendered":"<p>When you want to create any APIs for web\/mobile applications or any REST APIs, you must have to convert your response to a JSON object.<\/p>\n<p>Let&#8217;s discuss how we can build API response through the Laravel Eloquent model with the relationship to arrays to JSON.<\/p>\n<p>We&#8217;ve different types of processes in Laravel to make our response for APIs and for the frontend views.<\/p>\n<p>Those are below:<\/p>\n<p>1. By default Laravel Eloquent model provide the response in an object, and we need to convert it to the array and which will be passed through a Laravel response to the API as a JSON object.<\/p>\n<p>For Ex.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">$user = User::with('roles')-&gt;first();\r\nreturn response ([\r\n    'success' =&gt; true,\r\n    'message' =&gt; 'User data with roles',\r\n    'data' = [\r\n        'user' =&gt; $user-&gt;toArray(),\r\n    ]\r\n], 200);\r\n<\/pre>\n<p>The same way we can get a response like this:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">json_decode(User::with('roles')-&gt;get()-&gt;toJson(), true);<\/pre>\n<p>2. To pass a static collection in response to the API we can use the below process:<br \/>\nEx.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">$collection = collect([\r\n    \u2018f_name\u2019 =&gt; fake()-&gt;firstName(),\r\n    \u2018l_name\u2019 =&gt; fake()-&gt;lastName(),\r\n]);\r\n$collection-&gt;toArray();\r\n<\/pre>\n<p>3. After the Laravel 5.5 version release it provides us to convert our data (JSON\/Array) easily as per our requirement. Laravel&#8217;s resource classes allow you to expressively and easily transform your models and model collections into JSON\/Array.<\/p>\n<p>To create a resource class, we need to run the below command:<br \/>\nTerminal command: php artisan make: resource UserResource<\/p>\n<p>Resources extend the Illuminate\\Http\\Resources\\Json\\Resource class. Our UserResource will be like this:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">&lt;?php\r\n \r\nnamespace App\\Http\\Resources;\r\n \r\nuse Illuminate\\Http\\Resources\\Json\\Resource;\r\n \r\nclass UserResource extends Resource\r\n{\r\n    \/**\r\n     * Transform the resource into an array.\r\n     *\r\n     * @param  \\Illuminate\\Http\\Request\r\n     * @return array\r\n     *\/\r\n    public function toArray($request)\r\n    {\r\n        return [\r\n            'id' =&gt; $this-&gt;id,\r\n            'name' =&gt; $this-&gt;name,\r\n            'email' =&gt; $this-&gt;email,\r\n            'created_at' =&gt; $this-&gt;created_at,\r\n            'updated_at' =&gt; $this-&gt;updated_at,\r\n        ];\r\n    }\r\n}\r\n<\/pre>\n<p>To, use this Resource and get the data:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">use App\\User;\r\nuse App\\Http\\Resources\\UserResource;\r\n\r\npublic function index(){\r\n    return new UserResource(User::find(1));\r\n}\r\n<\/pre>\n<p>This will be useful for the single record to convert. To convert our full collection laravel provides us a facility to create a separate collection resource which will extend the Illuminate\\Http\\Resources\\Json\\ResourceCollection class.<\/p>\n<p><strong>Terminal command:<\/strong> php artisan make: resource User &#8211;collection \/ php artisan make:resource UserCollection<\/p>\n<p>Through the use of UserCollection we can convert our full collection. We can pass other static parameters. Also, it&#8217;ll be like this:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">&lt;?php\r\n \r\nnamespace App\\Http\\Resources;\r\n \r\nuse Illuminate\\Http\\Request;\r\nuse Illuminate\\Http\\Resources\\Json\\ResourceCollection;\r\n \r\nclass UserCollection extends ResourceCollection\r\n{\r\n    \/**\r\n     * Transform the resource collection into an array.\r\n     *\r\n     * @return array&lt;int|string, mixed&gt;\r\n     *\/\r\n    public function toArray(Request $request): array\r\n    {\r\n        return [\r\n            'data' =&gt; $this-&gt;collection,\r\n            'links' =&gt; [\r\n                'self' =&gt; 'link-value',\r\n            ],\r\n        ];\r\n    }\r\n}\r\n<\/pre>\n<p>To, use this Resource and get the data:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">use App\\Http\\Resources\\UserCollection;\r\nuse App\\Models\\User;\r\n\r\npublic function index(){\r\n    return new UserCollection(User::all());\r\n}\r\n<\/pre>\n<p>We can customise our UserResource as per our requirement to get a response as a JSON or Array. Use this type of Resource we don&#8217;t want to convert our record, It&#8217;ll be automatically converted. The benefits of using resources are:<\/p>\n<ul>\n<li>We can use nested Resources\/Collections<\/li>\n<li>Convert relationship data into the Resource<\/li>\n<li>To Getting data conditionally can be done easily<\/li>\n<li>Pass our custom attributes with conditionally<\/li>\n<\/ul>\n<p>So, you can convert your data as per your requirement with the use or -&gt;toArray()\/-&gt;toJson() and with the resource. But, the preferred way is to use Resource\/Collection.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>When you want to create any APIs for web\/mobile applications or any REST APIs, you must have to convert your response to a JSON object. Let&#8217;s discuss how we can build API response through the Laravel Eloquent model with the relationship to arrays to JSON. We&#8217;ve different types of processes in Laravel to make our [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":8485,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"inline_featured_image":false,"footnotes":""},"categories":[10],"tags":[],"class_list":["post-8146","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-laravel"],"acf":[],"_links":{"self":[{"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/posts\/8146"}],"collection":[{"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/comments?post=8146"}],"version-history":[{"count":1,"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/posts\/8146\/revisions"}],"predecessor-version":[{"id":8147,"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/posts\/8146\/revisions\/8147"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/media\/8485"}],"wp:attachment":[{"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/media?parent=8146"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/categories?post=8146"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/tags?post=8146"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}