Skip to content

Instantly share code, notes, and snippets.

@deepak-cotocus
Last active August 12, 2024 23:51
Show Gist options
  • Save deepak-cotocus/4da0985eaa3355f4654b861edaec86e6 to your computer and use it in GitHub Desktop.
Save deepak-cotocus/4da0985eaa3355f4654b861edaec86e6 to your computer and use it in GitHub Desktop.
How to Create Laravel Eloquent API Resources to convert model collections into JSON(Part 1).

Introduction:

What is API Resources in Laravel

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:

STEP 1: Generating Resources

  • 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 the Illuminate\Http\Resources\Json\JsonResource class:

php artisan make:resource User resources

STEP 2: Concept Overview

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);
    }
}

STEP 3: Add below Changes in web.php file

<?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);
});

STEP 4: All set to go

  • Here my Application is 'demo-app' and its virtual host url is http://demo-app/. So i will open browser and hit: http://demo-app/json and see tha magic of LARAVEL RESOURCES

resources-json

My basic recommendation for learning : Eloquent: API Resources

Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment