In Laravel, the default behavior of an API Resource Collection is to use a collection of Eloquent models. However, if you want to use an array of data instead of Eloquent models in a Resource Collection, you can achieve this by customizing the collection transformation.

To use an array of data in a Resource Collection, follow these steps:

  1. Create a new Resource Collection: Create a new Resource Collection using the following Artisan command:
bash
php artisan make:resource MyResourceCollection

This will generate a new Resource Collection file in the app/Http/Resources directory.

  1. Customize the Resource Collection: Open the newly created MyResourceCollection.php file and modify the toArray() method to handle arrays instead of Eloquent models. The toArray() method should transform the collection items into an array format.
php
<?php namespace App\Http\Resources; use Illuminate\Http\Resources\Json\ResourceCollection; class MyResourceCollection extends ResourceCollection { public function toArray($request) { return $this->collection->map(function ($item) { // Here, you can handle each item in the collection. // If $item is an Eloquent model, you can convert it to an array using $item->toArray(). // If $item is already an array, you can return it as is. // Example: // return $item instanceof \Illuminate\Database\Eloquent\Model ? $item->toArray() : $item; return $item; })->all(); } }
  1. Use the Custom Resource Collection: In your controller or wherever you are returning the API response, use the custom Resource Collection.

For example, in your controller:

php
use App\Http\Controllers\Controller; use App\Http\Resources\MyResourceCollection; class MyController extends Controller { public function index() { // Assuming $data is an array of data (not Eloquent models). $data = [ ['id' => 1, 'name' => 'Item 1'], ['id' => 2, 'name' => 'Item 2'], // ... ]; return new MyResourceCollection($data); } }

Now, when you call the index() method on your controller, it will return the API response using the custom Resource Collection, which transforms the array of data into the desired format for the API response.

By following these steps, you can use a custom array of data in a Resource Collection in Laravel instead of Eloquent models. This allows you to have more flexibility when constructing API responses for different scenarios.

Have questions or queries?
Get in Touch