6

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.

4
  • If you don't want to remove the ConvertEmptyStringsToNull middleware you could just use a one liner ternary statement, like:$property->bedrooms = $request->bedrooms ?: 0; Commented Jul 20, 2017 at 1:34
  • Cheers Aaron! I guess Rob's is technically the most correct answer but that shorthand is real handy too. Commented Jul 20, 2017 at 1:50
  • Yeah, I agree! Just a trick if you need to use that middleware in other parts of your application :) Commented Jul 20, 2017 at 1:51
  • 1
    This should work with decent PHP versions: $property->bedrooms = $request->input('bedrooms') ?? 0; Commented May 28, 2019 at 8:05

1 Answer 1

8

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,
    ];
Sign up to request clarification or add additional context in comments.

1 Comment

Ahhh yes. Thanks for that, Rob!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.