Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

junedc's avatar

Laravel Resource rule exclude_empty except a certain fields

In laravel resource we have this

public function rules()
{
    return [
        '*' => 'exclude_empty',
    ];
}


public function toArray($request): array
{

 return [
        'application_id'        => 'xxxx',
        'application_type'      => 'yyyy',
        'show_me'                => null,
        'andmore         =>  'lots more below'
     ]
}

because of the rules, show_me which is null does not show in the return value. How can i add only show_me even if null , but keeping the exclude_empty in the rules?

0 likes
2 replies
LaryAI's avatar
Level 58

Certainly! In Laravel API Resources, the exclude_empty rule will remove any fields with empty values (like null) from the response. If you want to always include a specific field (e.g., show_me) even if it's null, you can override the behavior for that field in your toArray method.

Here's how you can do it:

  1. Temporarily set a non-empty value for show_me before the rules are applied, then set it back to null after the rules are processed.
  2. Or, append show_me after the rules are applied.

The cleanest approach is to add show_me after the resource array is filtered by the rules. For example:

public function toArray($request): array
{
    // Build your array as usual
    $data = [
        'application_id'   => 'xxxx',
        'application_type' => 'yyyy',
        // 'show_me' is intentionally omitted here
        // ... other fields ...
    ];

    // Add 'show_me' explicitly, even if it's null
    $data['show_me'] = $this->show_me; // or null, or whatever value you want

    return $data;
}

If you want to keep your array definition clean and still use the exclude_empty rule, you can do this:

public function toArray($request): array
{
    $data = [
        'application_id'   => 'xxxx',
        'application_type' => 'yyyy',
        // ... other fields ...
    ];

    // After exclude_empty removes empty fields, add 'show_me' back
    $array = parent::toArray($request); // This applies the rules

    $array['show_me'] = $this->show_me; // or null

    return $array;
}

Summary:

  • Define your resource fields as usual.
  • After the rules (like exclude_empty) are applied, add the field(s) you want to always include, even if they are null.

This way, show_me will always be present in the response, regardless of its value, while all other fields will respect the exclude_empty rule.

junedc's avatar

not working, as solution is somehow hacky and it doesnt work. can we add something to rules to except certain fields

Please or to participate in this conversation.