What are Resources in Laravel
In Laravel, Resources (also called API Resources) are used to transform your data (usually models) into JSON format in a clean and structured way—mainly for APIs.
🔹 Simple Meaning
A Resource = Data Formatter for APIs
It controls:
“How your data should be shown to the user (client).”
🧠 Why Use Resources?
Without resources, you might return raw model data:
return User::all();
But with resources, you can:
- Customize output
- Hide sensitive fields (like passwords)
- Format data properly
- Add extra fields
🔧 Example
Step 1: Create Resource
php artisan make:resource UserResource
Step 2: Define Output Format
use Illuminate\Http\Resources\Json\JsonResource;
class UserResource extends JsonResource
{
public function toArray($request)
{
return [
'id' => $this->id,
'name' => $this->name,
'email' => $this->email,
];
}
}
Step 3: Use in Controller
use App\Http\Resources\UserResource;
public function index()
{
return UserResource::collection(User::all());
}
👉 Now your API returns clean, controlled JSON.
📦 Example Output
[
{
"id": 1,
"name": "Hanzala",
"email": "hanzala@example.com"
}
]
🔁 Resource vs Model
| Feature | Model | Resource |
|---|---|---|
| Purpose | Database interaction | Data formatting (API response) |
| Output | Raw data | Structured JSON |
| Control | Less | Full control |
🎯 Types of Resources
-
Single Resource
return new UserResource($user); -
Collection Resource
return UserResource::collection($users);
💡 Extra Features
-
Add relationships:
'posts' => PostResource::collection($this->whenLoaded('posts')) -
Add conditional fields:
'email' => $this->when($this->isAdmin(), $this->email)
🧩 In Short
Resources in Laravel = A layer that formats and controls how your data is returned in APIs.