In Laravel, if I've set a default value of 0 for all my integers, how can I get it to just go with its default if the request is null?
I've tried:
$property->bedrooms = $request->input('bedrooms', 0);
But it still just tries to set it as null and throws an error, as I'm assuming that's just for if the value doesn't exist at all.
Of course, I could go:
if($request->bedrooms){
$property->bedrooms = $request->bedrooms;
}else{
$property->bedrooms = 0;
}
...but that seems rather verbose.
Is there a neater solution I'm missing? Default values are sorta useless if you need to use an if/else every time anyway, surely.
In Laravel 5.4, they added the ConvertEmptyStringsToNull middleware which essentially overrides the $request->input() default value as if the field is not present in the request, it will add it to the request with a value of null.
$request->input(field, default value) will work again if you comment out the middleware in app\Http\kernel.php
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,
// \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With