首页 > 解决方案 > Laravel set default value if request value is null

问题描述

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

标签: laravelrequestmigrationdefault-value

解决方案


另一种方式:在 Model-Class 中定义 Mutators。

使用 Mutators,您可以定义为给定值设置为数据库值的内容。

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

在 Customer.php 添加方法。

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

public function setVatNumberAttribute($value)
{
    $this->attributes['vat_number'] = $value ?? 'BE';
}

推荐阅读