Laravel - API Resources - Writing Resource Collections

While resources transform a single model into an array, resource collections transform a collection of models into an array. However, it is not absolutely necessary to define a resource collection class for each one of your models since all resources provide a collection method to generate an "ad-hoc" resource collection on the fly:

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

However, if you need to customize the meta data returned with the collection, it is necessary to define your own resource collection:

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

Like singular resources, resource collections may be returned directly from routes or controllers:

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