# How to Globally Remove Null Values from Laravel 12 API Resources

By Dinesh Uprety
Published: 2025-12-27
Updated: 2025-12-27
Canonical: https://laranepal.com/blog/how-to-globally-remove-null-values-from-laravel-12-api-resources

# How to Globally Remove Null Values from Laravel 12 API Resources

When building APIs with **Laravel 12**, clean and consistent JSON responses are essential. One common issue developers face is dealing with **null values** in API resources. Repeating filtering logic in every resource quickly becomes messy and violates the **DRY (Don’t Repeat Yourself)** principle.

This article walks through a **clean and scalable solution**: creating a custom base resource that automatically removes null values from all API responses.

---

## 🚀 The Problem with Repeating Null Filters

By default, Laravel’s `JsonResource` includes all attributes—even those with `null` values. This can result in:

- Bloated API responses
- Inconsistent data output
- Repetitive filtering logic in every resource

Manually filtering null values inside each resource works, but it’s not maintainable in the long run.

---

## ✅ The Solution: A BaseJsonResource

The best approach is to create a **custom base resource** that handles null filtering globally. All your API resources will then extend this base class.

---

## 🔹 Step 1: Create a Base Resource

Create a new file at: `app/Http/Resources/BaseJsonResource.php`

```php
<?php

namespace App\Http\Resources;

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

class BaseJsonResource extends JsonResource
{
    /**
     * Remove null values from resource output.
     */
    public function toArray(Request $request): array
    {
        $data = parent::toArray($request);

        return collect($data)
            ->filter(fn ($value) => !is_null($value))
            ->all();
    }
}

```

This class overrides `toArray()` and automatically strips out all `null` values before returning the response.

---

## 🔹 Step 2: Extend the Base Resource

Instead of extending `JsonResource`, extend `BaseJsonResource` in your resources.

```php

<?php

namespace App\Http\Resources;

class UserResource extends BaseJsonResource
{
    public function toArray($request): array
    {
        return [
            'id'         => $this->id,
            'email'      => $this->email,
            'firstname'  => $this->firstname,
            'lastname'   => $this->lastname,
            'nickname'   => $this->nickname,
            'gender'     => $this->gender,
            'roles'      => $this->getRoleNames(),
            'dob'        => $this->dob,
            'height'     => $this->height,
            'weight'     => $this->weight,
            'created_at' => $this->created_at,
            'updated_at' => $this->updated_at,
        ];
    }
}

```

Any attribute that is `null` will now be **automatically excluded** from the API response.

---

## 🔹 Step 3: Use the Resource

```php
<?php

return new UserResource($user);
```

No extra filtering logic is needed.

---

## 🎯 Benefits of This Approach

- **DRY Code** – No repeated filtering logic
- **Consistency** – All resources behave the same
- **Scalability** – Easy to modify filtering rules later
- **Cleaner APIs** – Smaller, more readable responses

You can later extend this logic to remove empty strings or empty arrays — all from one place.

---

## 🏁 Conclusion

Creating a `BaseJsonResource` is the **cleanest and most maintainable way** to globally hide null values in Laravel 12 API resources. It keeps your codebase organized, your API responses clean, and your future self happy.

---
