Generating Resources In Laravel
To generate a resource class, you may use the make:resource
Artisan command. By default, resources will be placed in the app/Http/Resources
directory of your application. Resources extend the Illuminate\Http\Resources\Json\JsonResource
class:
php artisan make:resource User
Resource Collections
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.
To create a resource collection, you should use the --collection
flag when creating the resource. Or, including the word Collection
in the resource name will indicate to Laravel that it should create a collection resource. Collection resources extend the Illuminate\Http\Resources\Json\ResourceCollection
class:
php artisan make:resource Users --collection
php artisan make:resource UserCollection
Before diving into all of the options available to you when writing resources, let's first take a high-level look at how resources are used within Laravel. A resource class represents a single model that needs to be transformed into a JSON structure.
For example, here is a simple User
resource class:
Create user resource using below command
php artisan make:resource User
Open app\Resources\User.php file to implement below code
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class User extends JsonResource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
return [
'id' => $this->id,
'name' => $this->name,
'email' => $this->email,
'created_at' => $this->created_at,
'updated_at' => $this->updated_at,
];
}
}
Every resource class defines a toArray
method which returns the array of attributes that should be converted to JSON when sending the response. Notice that we can access model properties directly from the $this
variable. This is because a resource class will automatically proxy property and method access down to the underlying model for convenient access. Once the resource is defined, it may be returned from a route or controller:
For Example
Create Route in Web.php file as below
Route::get('/fulluserdata ', 'demoController@fulluserdata')->name('fulluserdata');
Create demoController and implement code to get all data from user table
php artisan make:controller demoController -mcr
Open demoController.php in app\Http\Controller folder and implement code as below
<?php
namespace App\Http\Controllers;
use App\Http\Resources\User as UserResource;
use App\User;
class demoController extends AppBaseController
{
public function Users()
{
return new UserResource(User::find(1));
}
}