【问题标题】:Laravel set default value if request value is null如果请求值为空,Laravel 设置默认值
【发布时间】:2021-01-15 22:43:53
【问题描述】:

我正在尝试为 laravel 迁移设置默认值。我正在使用 SQLite。

当我尝试使用分配了默认值的字段插入记录时,返回错误:SQL 错误或缺少数据库(表客户没有名为 country 的列)

这是迁移脚本:

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

控制器:

     * 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');
    }

请求:

 /**
     * 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'
        ];
    }

我要执行的sql脚本:

来自数据库 GUI 的一些屏幕截图

【问题讨论】:

标签: laravel request migration default-value


【解决方案1】:

如果以上方法都不行,试试这个

isset(request->requested_value)?requested_value:default_value

【讨论】:

    【解决方案2】:

    另一种方式:在 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';
    }
    

    【讨论】:

      【解决方案3】:

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

      #Solution 1 - 在保存前直接设置默认值

      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 - 在 FormRequest 中设置默认值 => prepareForValidation()

      如果您不熟悉laravel form request validation,请查看此链接: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
          ]);
      }
      

      #案例 2:if input is null => store null

      对于这种情况,您只需将 nullable() 添加到您的迁移中。

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

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

      在这种情况下,default() 将有意义;所以它只需要在迁移中将default() 添加到您的字段中。如下:

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

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

      此案例与案例 2

      重复

      希望帮助!

      【讨论】:

        【解决方案4】:

        我通过在迁移中添加 nullable 来解决它,然后检查 value 是否为 null。

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

        这比将每个值都放在创建中要少。

        【讨论】:

        • 但是你做了两次同样的事情。创建然后再次更新。您可以一次性完成。有时多几行代码会更好:)
        • 你是对的,但是如果模型有 20 个字段,则更难维护,并且对于模型的未来更新,这将始终有效。否则我也必须更新此功能。
        【解决方案5】:

        您已在数据库层设置了默认值。但它不能为空。这导致了这里的问题。您的请求国家/地区为空,并且您在创建新行时分配了该空值。要么你必须使用 nullable 来插入空值,要么你必须在创建时设置一个值。

        用于数据库

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

        对于您的情况,这不是一个好的解决方案。所以你可以使用一些东西

        Customer::create([
            'name' => $request->name,
            'country' => $request->country ?? 'BELGIË',
            //other attributes
        ]);
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2017-10-15
          • 2017-03-26
          • 1970-01-01
          • 2016-01-02
          • 2013-03-23
          • 1970-01-01
          • 2018-11-23
          相关资源
          最近更新 更多