LARAVEL's resource classes allow you to expressively and easily transform your models and model collections into JSON.Basically you can generate a nice json formatted data right from Eloquent. Laravel's resource classes allow you to expressively and easily transform your models and model collections into JSON. Let’s learn how to generate api resources.Consider you have a user table in your database and you want to generate api resources for your User model.Run following command on your terminal window while being on laravel project root directory:
- Run this Command to generate a resource class.
- By default, resources will be placed in the
app/Http/Resources
directory of your application. Resources extend theIlluminate\Http\Resources\Json\JsonResource
class:
php artisan make:resource User
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:
+Change the content of above file as shown below.
<?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 parent::toArray($request);
}
}
<?php
use App\User;
use App\Http\Resources\User as UserResource;
Route::get('/', function () {
return view('welcome');
});
Route::get('/json', function () {
$users = User::first();
return new UserResource($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