2

I am learning laravel 5.4. I know there is a new global middleware to convert request input empty string to null. But I have a question, the url like:http://localhost/choosePlan?type=1. I get type filed value in my controller action. If there is no type filed in request input or the value is empty, I want to set default type value to 1. So, in my controller action, I write like this:

$type = $request->input('type',1);

Only I access http://localhost/choosePlan I can get type default value. If I access like http://localhost/choosePlan?type or http://localhost/choosePlan?type= I still get type is null. So I think the default value for input method only works fine if no filed name in request body right? And how can I do to solve above problem? Like determine type is null and then set it to default value 1? I can't disable ConvertEmptyStringsToNull middleware cause it is used somewhere else. Thanks.


Update: I just test disable ConvertEmptyStringsToNull middleware now I get type is empty string. Maybe I misunderstand this method, I think the default value is just for specified filed not present in request not for filed name present in request but value is empty, is that right? Oh, my god, this means I also misunderstand it in Laravel 5.2.

2 Answers 2

7

If you want to add a default value programmatically without needing to disable ConvertEmptyStringsToNullyou you can do something like :

  $type = $request->input('type') ?: 1; // You can set whatever value you want
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for this idea. Everyone else, see: laravel.com/docs/5.4/requests#input-trimming-and-normalization
7

You may pass a default value as the second argument to the input method. This value will be returned if the requested input value is not present on the request:

$name = $request->input('name', 'Sally');

Comments

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.