Lesson 35 of 50
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:
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.
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.
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.
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.
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.
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.
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.
Create a Student API using Laravel Resources.
Bonus Task:
Rename the response field name to
student_name without changing the database.
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?