Do you know Laravel have released version 9.46?

The Laravel team released 9.46 this week with two JsonResource methods to conditionally include resource properties, updates to the decimal validation rule and more.

Patrick Wan
2 min readJan 14, 2023

There have 3 new updates for Laravel version 9.46.

  1. Add “whenHas” to the JSONResource
  2. JsonResource “unless” method
  3. Decimal validation rule supports signed numbers

Let’s get in more detail.

Add “whenHas” to the JSONResource

Michael Nabil contributed a whenHas() method to the JsonResource, which gives you the ability to conditionally include attributes in a Response when an attribute is found on a model.

For example, this provides a clean way to define an attribute conditionally:

public function toArray($request)
{
return [
'id' => $this->id,
'name' => $this->name,
'email' => $this->whenHas('email'),
];
}

You can also define a Closure as the default:

public function toArray($request)
{
return [
'id' => $this->id,
'name' => $this->name,
'email' => $this->whenHas('email', function () {
return 'default value';
}),
];
}

JsonResource “unless” method

--

--

Patrick Wan

My name’s Patrick. I’m a Software Developer, experience in Laravel, Vue Js, React Js, Livewire, Jquery, Codegniter, NPM, GIT. I have 5 years plus experience.