Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel - Use default value if input is null

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.

like image 317
MitchEff Avatar asked Jul 20 '17 01:07

MitchEff


1 Answers

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,
    ];
like image 116
Rob Fonseca Avatar answered Oct 01 '22 03:10

Rob Fonseca