
In addition to generating resources that transform individual models, you may generate resources that are responsible for transforming collections of models. This allows your response to include links and other meta information that is relevant to an entire collection of a given resource.
Collection resources extend the Illuminate\Http\Resources\Json\ResourceCollection class:
In previoes lessons we have seen how to generate json data of single object. Now we are going to see how to generatet Collection of Objects.
php artisan make:resource UserCollection
Or
php artisan make:resource User --Collection
- Now we anve another resource
UserCollection
Keep <your-app>\app\Http\Resources\User
as it is.
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\Resource;
use Illuminate\Support\Facades\Log;
class User extends Resource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
return [
'name' => $this->name,
'email' => $this->email,
'profile' => url('/user/'. $this->id . '/'),
];
}
}
Open <your-app>\app\Http\Resources\UserCollection
.
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\ResourceCollection;
class UserCollection extends ResourceCollection
{
/**
* Transform the resource collection into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
return parent::toArray($request);
}
}
<?php
use App\User;
use App\Http\Resources\User as UserResource;
use App\Http\Resources\UserCollection;
Route::get('/', function () {
return view('welcome');
});
Route::get('/json', function () {
$users = User::all();
return new UserCollection($users);
});
- Here my Application is
'demo-app'
and its virtual host url ishttp://demo-app/
. So i will open browser and hit:http://demo-app/json
and see tha magic of LARAVEL RESOURCES
My basic recommendation for learning : Eloquent: API Resources



MotoShare.in is your go-to platform for adventure and exploration. Rent premium bikes for epic journeys or simple scooters for your daily errands—all with the MotoShare.in advantage of affordability and ease.