Skip to content

Instantly share code, notes, and snippets.

@deepak-cotocus
Last active August 22, 2020 08:06
Show Gist options
  • Save deepak-cotocus/817bea0092866d81df731273465b2518 to your computer and use it in GitHub Desktop.
Save deepak-cotocus/817bea0092866d81df731273465b2518 to your computer and use it in GitHub Desktop.
How to Create Laravel Eloquent API Resources to convert model collections into JSON(Part 2).

Introduction:

How to generate customized Json data using resource in Laravel?

In Our previous tutorial we have seen how to generate json data in which we just did a Direct Map of our User database table.

Now, We are going to play arround Json data as per our requirement. Every Time Requirements will be diffrent Right...... So we are gona generate different numbers of data in many ways... Just go for it Guys...!

  • If i don't need id,created_at and updated_at field in my Json Object. what would i do then...

  • 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: Concept Overview

+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 [
            
            'name' => $this->name,
            'email' => $this->email,
     
        ];
    }
}

STEP 2: Add below Changes in web.php file

  • If you already have below lines of code in your web.php, then no need of any change.
<?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

resources-json-customized1

My basic recommendation for learning : Eloquent: API Resources

Thanks

@deepak-cotocus
Copy link
Author

resources-json-customized1

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