3

Can I set a default value to a not-existing field in a FormRequest in Laravel?

For example, if a field called "timezone" does not exist in the incoming request, it get set to "America/Toronto".

3
  • You typically do this at the database level during migration. E.G. ->default('America/Toronto'). Commented Feb 10, 2020 at 18:19
  • Try and share your code next time. You can get better solutions Commented Feb 10, 2020 at 18:34
  • 2
    @DigitalDrifter it shouldn't be at the database level, because a request might not deal with database at all. Commented Feb 10, 2020 at 19:21

4 Answers 4

8

in request class add

public function prepareForValidation()
{
    $this->mergeIfMissing([
        'timezone'  => 'America/Toronto'
    ]);
}
Sign up to request clarification or add additional context in comments.

1 Comment

it works for $request->all(), but does not work for $request->validated()
7

Well I wrote a trait for this, which checks a function called 'defaults' exist in the form request it will replace the default values

trait RequestDefaultValuesTrait {


    protected function prepareForValidation(){

        // add default values 
        if( method_exists( $this, 'defaults' ) ) {
            foreach ($this->defaults() as $key => $defaultValue) {
                if (!$this->has($key)) $this->merge([$key => $defaultValue]);
            }
        }
    } 
}

the thing that you need to do is adding this trait to FormRequest class and then add a function like this:

protected function defaults()
{
    return [
        'country'   => 'US',
        'language'  => 'en',
        'timezone'  => 'America/Toronto',
    ];
}

Being honest I don't link this method, but It works.

2 Comments

Why you don't like it?
I have used this but now I need default values for an array variable like user['name'] = "Jhon" and this will not work
5

Try this

if(!$request->has('timezone') {
    $request->merge(['timezone' =>'America/Toronto']);
}  

Comments

0

I'm not so sure if you need to do it in this way, but if you want to:

class CreateUpdateDataFormRequest extends Request
{

    public function authorize()
    {
        return true;
    }

    public function rules()
    {
        return [];
    }

    protected function getValidatorInstance()
    {
        $data = $this->all();

        if(!isset($data['timezone'])) {
            $data['timezone'] = 'America/Toronto';
            $this->getInputSource()->replace($data);
        }

        // modify data before sending to validator
        return parent::getValidatorInstance();
    }

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.