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.
--
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';
}),
];
}
JsonResource “unless” method
Michael Nabil contributed an unless()
method for retrieving a value if the condition resolves to false
:
public function toArray($request){
$someCondition = false;
return [
'id' => $this->id,
'name' => $this->name,
// Email will be included, with `true` will not.
'email' => $this->unless($someCondition, 'email'),
];
}
Decimal validation rule supports signed numbers
@Pusparaj contributed an update to the decimal
validation rule that supports signed number (i.e., -5.5
, +1.5
, etc.):
$v = new Validator(
$trans,
['foo' => '-1.234'],
['foo' => 'Decimal:2,3']
);
$this->assertTrue($v->passes());
If you enjoyed to read more articles about Laravel please subscribe my channel. ^^