---
title: 'Laravel Tip: Conditional Fields in API Resources'
source: 'https://youtube.com/watch?v=lGvr4ppAj0s'
video_id: 'lGvr4ppAj0s'
date: 2026-08-14
duration_sec: 53
---

# Laravel Tip: Conditional Fields in API Resources

> Source: [Laravel Tip: Conditional Fields in API Resources](https://youtube.com/watch?v=lGvr4ppAj0s)

## Summary

This video presents a concise Laravel tip for Eloquent API resources, demonstrating how to conditionally include fields in API responses. It contrasts a verbose if-statement approach with Laravel's built-in `when` and `mergeWhen` methods for cleaner, more readable code.

### Key Points

- **Problem: Conditional fields in API resources** [00:00] — When building Eloquent API resources, you often need to return certain fields only under specific conditions, such as when the authenticated user is an admin. The typical approach involves defining an array and then adding an if statement to append additional values.
- **Solution: Laravel's `when` method** [00:18] — Laravel provides a shorter syntax using the `when` method. For a single field like 'phone', you can write `'phone' => $this->when($condition, $value)`. The field is only included in the response if the condition is true; otherwise, the key is omitted entirely.
- **Solution: `mergeWhen` for multiple fields** [00:31] — For multiple attributes, use the `mergeWhen` method. It takes a condition and an array of fields to merge into the resource. This keeps the code clean and avoids verbose if-else blocks.
- **Call to action** [00:48] — The video ends with a prompt to subscribe to the Laravel Daily channel for more Laravel tips and longer tutorials.

### Conclusion

Laravel's `when` and `mergeWhen` methods offer a concise and elegant way to conditionally include fields in API resources, improving code readability and maintainability.

## Transcript

Laravel tip for Eloquent API resources. What if you want to return some fields only based on some conditions? Then you would probably define the array and then put if statement like this. So if there's a user and if that user is admin, then we add more values to the return. But Laravel has
a shorter syntax for that. You can achieve the same result by using this when or this merge when. If we're talking about one value to be returned like phone, it could be this one, then condition,
and the value, and this would be returned only if the user is admin. If they are not admin, then that key of the phone wouldn't be present in the API return result. For multiple attributes, you can use merge when, again condition, and then array to be returned or to be merged with this
array in the beginning. For more Laravel tips and longer tutorials, subscribe to my channel, Laravel Daily.
