Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save deepak-cotocus/4d7fdf5fd73e92b79f6560b607b9e096 to your computer and use it in GitHub Desktop.
Save deepak-cotocus/4d7fdf5fd73e92b79f6560b607b9e096 to your computer and use it in GitHub Desktop.
How to Create Laravel Eloquent API Resources to convert model collections into JSON(Part 3).

Json Resource with additional information along with standered values in json file

Introduction:

How to generate customized Json data using resource in Laravel with some additional information?

In Our previous tutorial we have seen how to generate customized Json data in which we had generated 2 field values from User tabel of database.

Now, Assuming Requirement: I need a json data of User Table along with below aditional data like

  1. Virsion
  2. attribution
  3. valid_as_of
  • If i need Virsion, attribution and valid_as_of, attribiutes in my Json Object. what would i do then...

We will add with(){} function with additional data in our User class as shown below:

  • Lets see where i will make Changes in code. NOte: Make sure you have Resourec folder with User class under <Your-app>\app\http\Resources

STEP 1: Adding with(){} with additional information.

<?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 . '/'),
     
        ];
    }
    
    public function with($request){
        return [
            'version' => '2.0.0',
            'attribution' => url('/terms-of-service'),
            'valid_as_of' => date('D, d M Y H:i:s'),
        ];
    }
}
 

STEP 2: keep below below Changes in web.php file as it was before

<?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 3: 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

addition-info-to-json-resource

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