Laravel set default value if request value is null
Asked Answered
P

6

7

I'm trying to set a default value to a laravel migration. I'm using SQLite.

When I try to insert a record with the field where a default value is assigned to, an error returns: SQL error or missing database (table customers has no column named country)

This is the migrationscript:

php
Schema::create('customers', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('contact_person_first_name');
            $table->string('contact_person_name');
            $table->string('contact_person_email_address');
            $table->string('address');
            $table->string('zipCode');
            $table->string('city');
            $table->string('country')->default("BELGIË");
            $table->string('vat_number')->default("BE");
            $table->timestamps();

The controller:

     * Store a newly created resource in storage.
     *
     * @param CreateCustomerRequest $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function store(CreateCustomerRequest $request)
    {
        Customer::create($request->validated());
        return response()->redirectTo('/customers');
    }

The request:

 /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'name' => 'required|string|min:2|max:255',
            'contact_person_first_name' => 'required|string|min:2|max:255',
            'contact_person_name' => 'required|string|min:2|max:255',
            'contact_person_email_address' => 'required|email',
            'address' => 'required|string|min:2|max:255',
            'zipCode' => 'required|string|min:4|max:10',
            'city' => 'required|string|min:2|max:255',
            'country' => 'nullable|string|min:2|max:255',
            'vat_number' => 'nullable|min:12|max:12'
        ];
    }

The sql script I want to execute: enter image description here

Some screenshots from the database GUI Database headers

enter image description here

Planometer answered 30/9, 2020 at 9:20 Comment(2)
Does this answer your question? Set default to NULL with laravel migrationTheophilus
This only set's the value to null.. It doesn't set any default valuePlanometer
O
5

#Case 1: if input is null => store a default value

#Solution 1 - Set default value directly before saving

public function store(CreateCustomerRequest $request)
{
    // Retrieve the validated input data...
    $validated = $request->validated();
    
    $validated['need_to_have_default_value'] = $validated['need_to_have_default_value'] ?? $defaultValue; // Replace $defaultValue with value that you want to set as default
    Customer::create(validated );

#Solution 2 - Set default value in FormRequest => prepareForValidation()

if you are not familiar with laravel form request validation see this link: https://laravel.com/docs/8.x/validation#form-request-validation

/**
 * Prepare the data for validation.
 *
 * @return void
 */
protected function prepareForValidation()
{
    $this->merge([
        'need_to_have_default_value' => $this->need_to_have_default_value ?? $defaultValue // Replace $defaultValue with value that you want to set as default
    ]);
}

#Case 2: if input is null => store null

For this case you just need to add nullable() to your migration.

$table->string('set_null_if_null')->nullable();

#Case 3: if input is not set/send => store default value

In this case, the default() will make sense; so it just need to add default() to your field in migration. like below:

$table->string('set_default_if_not_present')->default('any_default_value');

#Case 4: if input is not set/send => store null value

This case is duplicate of case 2

Hope help !

Oftentimes answered 9/4, 2021 at 21:19 Comment(0)
O
5

Another way: Define Mutators in the Model-Class.

With Mutators you can define, what is to set as database-value for a given value.

Look in Laravel/Docs/Eloquent/Mutators: https://laravel.com/docs/8.x/eloquent-mutators

In Customer.php add methods.

public function setCountryAttribute($value)
{
    $this->attributes['country'] = $value ?? 'BELGIË';
}

public function setVatNumberAttribute($value)
{
    $this->attributes['vat_number'] = $value ?? 'BE';
}
Ovalle answered 20/7, 2021 at 4:6 Comment(0)
S
1

you have set a default value in database layer. but it is not nullable. this is causing the problem here. your request country is null and you are assigning that null value when creating new row. either you have to use nullable to insert null value or you have to set a value when creating.

for database

$table->string('country')->nullable()->default("BELGIË");

this is not a good solution for your case. so you can use something

Customer::create([
    'name' => $request->name,
    'country' => $request->country ?? 'BELGIË',
    //other attributes
]);
Selmore answered 30/9, 2020 at 9:32 Comment(0)
B
-1

Try this if none of the above works

isset(request->requested_value)?requested_value:default_value

Buoyant answered 30/9, 2020 at 9:21 Comment(0)
P
-1

I solved it by adding nullable in the migration and then check if value is null.

$customer = Customer::create($request->validated());
        if ($customer->country == null) $customer->country= "BELGIË";
        if ($customer->vat_number == null) $customer->vat_number= "BE";
        $customer->save();

It's less work than putting every value in the create.

Planometer answered 30/9, 2020 at 10:14 Comment(2)
but you are doing the same thing twice. creating and then updating again. you can do this in a single go. sometimes few more lines of code is better :)Selmore
You are right, but if the model has 20 fields, it is harder to maintain and for future updates to the model, this will always work. Else I have to update this function as well.Planometer
T
-1

like use

public function rules()
{
    $rules = [
        'column_name' => ['required'], //boolean type
    ];

    return $rules;

}//end of rul


protected function prepareForValidation()
{
    $this->merge([
        'column_name' => request()->has('column_name') ?? '0',
    ]);

}//end of fun
Tevis answered 13/8, 2022 at 15:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.