How to assign a default value to form input - Laravel 8

1.8k views Asked by At

I have a registration form that will get data from users and send it to database

here is one of the inputs in the view page:

<div style="font-family: Frutiger;" class="mt-4 text-right">
                    <x-jet-label for="name" value="{{ __(' * First Name') }}" />
                    <x-jet-input id="name" class="block mt-1 w-full text-right border" type="text" name="name" :value="old('name')" required autofocus autocomplete="name" />
                </div>

so i want to make this input optional and be able to submit the form without any value but if its left empty i want the default value to be for example "name"

is there any solution for this through this code or through Mysql?

3

There are 3 answers

0
Abolfazl Mohajeri On

Maybe you have something like this in your controller that form data sent:

$request->validate([
    'name' => 'required',
    ...
]);

You should erase 'name' => 'required' from this.

But if you get database error you should add this to your migration:

$table->string('name')->nullable();
1
kemp On

One option is to set the initial value of the input to contain the value:

<x-jet-input id="name" class="block mt-1 w-full text-right border" type="text" name="name" :value="{{ old('name') ?? 'Default value' }}" required autofocus autocomplete="name" />
0
Daishi On

According to Laravel 8 documentation, the old() helper function accepts a second argument as a default value :

$value = old('field_name', 'default_value');

For more details see Helpers - Laravel - The PHP Framework For Web Artisans