Writing Resources
To Create Resources visit our Bajarangisoft site.
Resources are simple. They only need to transform a given model into an array. So, each resource contains a toArray
method which translates your model's attributes into an API friendly array that can be returned to your users:
<?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,
];
}
}
Route::get('/fulluserdata ', 'demoController@fulluserdata')->name('fulluserdata');
Create demoController and implement code to get all data from user model
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));
}
}
Relationships
If you would like to include related resources in your response, you may add them to the array returned by your toArray
method. In this example, we will use the Post
resource's collection
method to add the user's blog posts to the resource response:
<?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,
'posts' => PostResource::collection($this->posts),//accessing data from post
'created_at' => $this->created_at,
'updated_at' => $this->updated_at,
];
}
}
collection
method to generate an "ad-hoc" resource collection on the fly:
use App\Http\Resources\User as UserResource;
use App\User;
Route::get('/user', function () {
return UserResource::collection(User::all());
});
However, if you need to customize the meta data returned with the collection, it will be necessary to define a resource collection:
<?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 [
'data' => $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\User;
Route::get('/users', function () {
return new UserCollection(User::all());
});