user2
user2

Reputation: 59

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

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?

Upvotes: 1

Views: 2084

Answers (3)

Daishi
Daishi

Reputation: 14219

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

Upvotes: 0

kemp
kemp

Reputation: 703

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" />

Upvotes: 1

Abolfazl Mohajeri
Abolfazl Mohajeri

Reputation: 1987

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();

Upvotes: 0

Related Questions