如何在Laravel 8中存储多个复选框值

njthzxwz  于 2022-11-18  发布在  其他
关注(0)|答案(1)|浏览(138)

我是新的Laravel,我做了一个调查表与多个复选框存储在数据库中,当表单提交它只读最后输入这里是我的模型:

protected $fillable = ['Name',
                           'email',
                           'number',
                           'age',
                           'roles',
                           'recommend',
                           'options',
                           'comment'];
 protected $casts = ['options'=>'array'];

这里是我的控制器:

User::create($request->all());

    return redirect()->route('user.index')
    ->with('success','Info Added successfully');

移转:

$table->set ('options', ['Front-end Projects', 'Back-end Projects', 'Data Visualization', 'Challenges',
                     'Open Source Community', 'Gitter help rooms', 'Videos', 'City Meetups', 'Wiki', 'Forum', 'Additional Courses'
        ])->nullable();

这是我的刀锋

<input type="checkbox" name="options[]" value="Front-end Projects">Front-end Projects
  <br>
  <input type="checkbox" name="options[]" value="Back-end Projects">Back-end Projects
  <br>
  <input type="checkbox" name="options[]" value="Data Visualization">Data Visualization
  <br>
  <input type="checkbox" name="options[]" value="Challenges">Challenges
  <br>
  <input type="checkbox" name="options[]" value="Open Source Community">Open Source Community
  <br>
  <input type="checkbox" name="options[]" value="Gitter help rooms">Gitter help rooms
  <br>
  <input type="checkbox" name="options[]" value="Videos">Videos<br>
  <input type="checkbox" name="options[]" value="City Meetups">City Meetups<br>
  <input type="checkbox" name="options[]" value="Wiki">Wiki<br>
  <input type="checkbox" name="options[]" value="Forum">Forum<br>
  <input type="checkbox" name="options[]" value="Additional Courses">Additional Courses<be>

下面是我表模式:table schema
这是我尝试过的,但我得到了错误

nlejzf6q

nlejzf6q1#

我要做的是确保options列是一个文本字段,在设置属性时确保它被编码为json字符串,在检索时确保它被恢复为数组。

function setOptionsAttribute($values = null)
{
   if(null === $values) {
     $this->attributes['options'] = null;
   }
   $this->attributes['options'] = json_encode($values);
}

function getOptionsAttribute($value)
{
   if(null === $values){
     return null;
   }
   return json_decode($values,true);
}

相关问题