Laravel API Resources and JSON Responses

Lesson 35 of 50

70%
1. What Is an API Resource?

In Laravel, an API Resource transforms model data into a structured JSON response. It helps you control which fields are returned to the client.

For example, a Student model may contain:

id
name
email
password
created_at

An API Resource can return only the student's ID, name, and email instead of exposing every database field.

Benefits:

  • Controls the JSON response structure.
  • Keeps API responses consistent.
  • Helps prevent sensitive fields from being exposed.
  • Makes it easier to format relationships and dates.
2. Create an API Resource

Use the following Artisan command to create a resource for the Student model:

php artisan make:resource StudentResource

Laravel creates this file:

app/Http/Resources/StudentResource.php

Open the generated file and define the fields that should appear in the API response.

<?php

namespace App\Http\Resources;

use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;

class StudentResource extends JsonResource
{
    public function toArray(Request $request): array
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'email' => $this->email,
        ];
    }
}

The toArray() method determines how the resource is converted into an array for JSON output.

3. Return a Single Resource

You can return one student using StudentResource from a controller.

<?php

namespace App\Http\Controllers;

use App\Http\Resources\StudentResource;
use App\Models\Student;

class StudentController extends Controller
{
    public function show(string $id)
    {
        $student = Student::findOrFail($id);

        return new StudentResource($student);
    }
}

Define the route in routes/api.php:

use App\Http\Controllers\StudentController;
use Illuminate\Support\Facades\Route;

Route::get('/students/{id}', [StudentController::class, 'show']);

Example request:

GET /api/students/1

Assuming the student exists, Laravel returns the resource data as JSON.

4. Return Multiple Resources

Use StudentResource::collection() to transform a collection of students.

use App\Http\Resources\StudentResource;
use App\Models\Student;

public function index()
{
    $students = Student::all();

    return StudentResource::collection($students);
}

Route example:

Route::get('/students', [
    StudentController::class,
    'index'
]);

Example JSON data:

{
    "data": [
        {
            "id": 1,
            "name": "Rahul Kumar",
            "email": "rahul@example.com"
        },
        {
            "id": 2,
            "name": "Priya Singh",
            "email": "priya@example.com"
        }
    ]
}

Laravel normally wraps resource output in a data key. Resource collections can also include pagination links and metadata when paginated.

5. Customize JSON Field Names

You can change the field names returned by the resource without changing your database column names.

public function toArray(Request $request): array
{
    return [
        'student_id' => $this->id,
        'student_name' => $this->name,
        'email_address' => $this->email,
    ];
}

Example response:

{
    "data": {
        "student_id": 1,
        "student_name": "Rahul Kumar",
        "email_address": "rahul@example.com"
    }
}

Here, the database may still use the columns id, name, and email. Only the API response names change.

6. Add Conditional Fields

Sometimes you may want to include a field only when the required data is available.

public function toArray(Request $request): array
{
    return [
        'id' => $this->id,
        'name' => $this->name,
        'email' => $this->email,

        'course' => $this->whenLoaded('course'),
    ];
}

The whenLoaded() method includes the course relationship only when it has been loaded.

For example, load the relationship in the controller:

$student = Student::with('course')
    ->findOrFail($id);

return new StudentResource($student);

This example assumes the Student model has a relationship method named course(). The relationship must be defined before using it.

7. Return JSON Without an API Resource

Laravel also provides response()->json() for returning JSON directly.

public function profile()
{
    $student = [
        'id' => 1,
        'name' => 'Rahul Kumar',
        'course' => 'Laravel'
    ];

    return response()->json($student);
}

Example JSON response:

{
    "id": 1,
    "name": "Rahul Kumar",
    "course": "Laravel"
}

Use response()->json() for simple responses. Use API Resources when you need a reusable, consistent format for model data across multiple endpoints.

8. API Resource Best Practices
  • Return only the fields clients actually need.
  • Never expose passwords or private credentials.
  • Use consistent names for JSON fields.
  • Use pagination for large collections.
  • Load relationships intentionally to avoid unnecessary queries.
  • Use validation before storing or updating data.
  • Use authentication and authorization where required.
  • Test API responses with Postman or another API client.

Important:

API Resources format data; they do not automatically authenticate users or decide whether a user is allowed to access a record. Use Laravel authentication and authorization for those responsibilities.

9. Practice Assignment

Create a Student API using Laravel Resources.

  1. Create a Student model and migration with name, email, and course columns.
  2. Create the StudentResource using Artisan.
  3. Return only ID, name, and email from the resource.
  4. Create an API endpoint to display one student.
  5. Create another endpoint to display all students.
  6. Test both endpoints using Postman.

Bonus Task:

Rename the response field name to student_name without changing the database.

Quick Quiz

1. Which method defines the fields returned by an API Resource?




2. Which method transforms a collection using a Resource class?




3. What is the main purpose of an API Resource?