Laravel’s API Resources provide elegant methods for conditionally including attributes in your responses, allowing you to create flexible and efficient APIs that adapt to different contexts and permissions.
When building APIs, you often need to customize your responses based on different scenarios – such as showing certain fields only to admins, including related data only when requested, or adapting the response format based on the endpoint. Laravel’s API Resources provide powerful methods to handle these cases through conditional attributes.
Some key methods available are:
- ‘when()’: Includes an attribute only if a condition is true
- ‘whenLoaded()’: Includes relationships only if they’ve been loaded
- ‘whenNotNull()’: Includes an attribute only if it’s not null
- ‘whenHas()’: Includes an attribute only if it exists on the model
use IlluminateHttpRequest;
use IlluminateHttpResourcesJsonJsonResource;
class UserResource extends JsonResource
{
public function toArray(Request $request): array
{
return [
'id' => $this->id,
'name' => $this->name,
'email' => $this->when($request->user()->isAdmin(), $this->email),
];
}
}
Let’s explore a practical example of a product catalog API with conditional data:
<?php
namespace AppHttpResources;
use IlluminateHttpRequest;
use IlluminateHttpResourcesJsonJsonResource;
class ProductResource extends JsonResource
{
public function toArray(Request $request): array
{
return [
'id' => $this->id,
'name' => $this->name,
'slug' => $this->slug,
'price' => $this->price,
// Include full description only in detailed view
'description' => $this->when(
$request->route()->named('products.show'),
$this->description,
$this->excerpt
),
// Include stock info for authenticated users
'stock_level' => $this->when(
$request->user()?->can('view-inventory'),
$this->stock_count
),
// Include relationships when loaded
'category' => new CategoryResource($this->whenLoaded('category')),
// Include counts conditionally
'reviews_count' => $this->when(
$request->include_counts,
$this->reviews_count
),
// Include admin data
'profit_margin' => $this->when(
$request->user()?->isAdmin(),
fn() => $this->calculateProfitMargin()
),
];
}
}
Laravel’s conditional attributes in API Resources enable you to build context-aware responses while keeping your code clean and maintainable.
The post Dynamic API Response Control in Laravel Resources appeared first on Laravel News.
Join the Laravel Newsletter to get all the latest
Laravel articles like this directly in your inbox.
Source: Read MoreÂ