Member-only story
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.
2 min readJan 14, 2023
There have 3 new updates for Laravel version 9.46.
- Add “whenHas” to the JSONResource
- JsonResource “unless” method
- 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';
}),
];
}