Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Rioko's avatar
Level 1

Is it a good practice for retrieving GET request data and set default value for it ?

Hello guys, I curious about this method to get data from request. For example

// this is a custom validator create to validate the data and the rules is write according to the retrieve data // can just ignore this one $this->validator($request->all(), $rules);

// most important is this get method $name = $request->get('name', ''); $age = $request->get('age', 0); $type = $request->get('type', 1);

You can see that they define the var with the GET data from request and set a default value for it. So my question is, is it a good practice to have a default value when you get the data and why ? How will it affect the results when I use this method ?

0 likes
3 replies
Sinnbeck's avatar

It all depends on what you need the data for. I have several fields where I want a specific default. This could be a filter by date, that when empty should use today. But in some other cases I explicitly want null if nothing is selected, and therefor leave out the default. So just make sure you know exactly what you expect out of each request value and set the default that fits

1 like
Snapey's avatar

its good practice to validate that you get the values you need

I would not think it's good design to force a missing parameter to an empty string so that something else later does not break

1 like
Rioko's avatar
Level 1

@sinnbeck @snapey Sorry for late reply because lately I busy in review the code and forgot that I have asked the question.

@sinnbeck So this means that in some certain case it is good to have a default value when the request GET data is null or empty. But I also wonder if there is a validation for each request, why I still need the default value even though the request data has been validated ? Since you have been validated the request data not to be empty or null, but why still need to set the the default value for it ? You can just directly used the validated data.

@snapey As so far I have learn to use laravel, I agree with you but my scenario is that they already validate all the request data but they not using the validated data and use the request data with default value.

Please or to participate in this conversation.