Laravel - API Resources - Resource Collections

If you are returning a collection of resources or a paginated response, you should use the collection method provided by your resource class when creating the resource instance in your route or controller:

    
    use App\Http\Resources\UserResource;
    use App\Models\User;
    
    Route::get('/users', function () {
        return UserResource::collection(User::all());
    });
	

Note that this does not allow any addition of custom meta data that may need to be returned with your collection. If you would like to customize the resource collection response, you may create a dedicated resource to represent the collection:

    
    php artisan make:resource UserCollection
	

Once the resource collection class has been generated, you may easily define any meta data that should be included with the response:

    
     $this->collection,
                'links' => [
                    'self' => 'link-value',
                ],
            ];
        }
    }
	

After defining your resource collection, it may be returned from a route or controller:

    
    use App\Http\Resources\UserCollection;
    use App\Models\User;
    
    Route::get('/users', function () {
        return new UserCollection(User::all());
    });