我试图在我的应用程序中使用以下内容:
<div class="form-group">
<label for="genetics">Bell Albino</label>
<select name="genetics[]" class="form-control">
<option>N/A</option>
<option value="BA">Visual</option>
<option value="ba">Recessive</option>
</select>
</div>
<div class="form-group">
<label for="genetics">Tremper Albino</label>
<select name="genetics[]" class="form-control">
<option>N/A</option>
<option value="TA">Visual</option>
<option value="ta">Recessive</option>
</select>
</div>但是,当我尝试提交我的表单时,我会得到以下错误:
preg_replace(): Parameter mismatch, pattern is a string while replacement is an array
这是我的模型,不确定它是否有用:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Gecko extends Model
{
/**
* Fillable fields for a gecko
* @var array
*/
protected $fillable = [
'name',
'aquisition_date',
'morph',
'sex',
'genetics',
'bio',
'bred',
'hatchling',
'clutch',
'user_id'
];
/**
* A gecko has many photos
* @return \Illuminate\Database\Eloquent\Relations\HasMany;
*/
public function photos()
{
return $this->hasMany('App\GeckoPhoto');
}
/**
* A gecko has many weights
* @return \Illuminate\Database\Eloquent\Relations\HasMany;
*/
public function weights()
{
return $this->hasMany('App\Weight');
}
}存储方法:
public function store(GeckoRequest $request)
{
Gecko::create($request->all());
flash()->success('Success!', 'Your gecko has been added to the system');
return redirect()->action('GeckoController@show', [$request['name']]);
}GeckoRequest文件:
<?php
namespace App\Http\Requests;
use Auth;
use App\Http\Requests\Request;
class GeckoRequest extends Request
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'morph' => 'required',
'sex' => 'required',
'genetics' => 'required',
'name' => "required|unique:geckos,name,NULL,id,user_id," . \Auth::user()->id
];
}
}它只保存到数据库中的单词Array。
我肯定这很简单,但我不知道怎么解决
编辑:我需要将这些值作为json或逗号分隔的值添加到数据库中--实际上,它只需要使用多个具有相同名称数组的select标记,并将所有选定的字段保存到数据库表中。
发布于 2015-10-21 18:08:00
问题是,您正在使用select存储多个值,但同时试图在表的文本字段中存储数组(在表的架构中,有$table->text('genetics');)。提交的表单将传递字段genetics的选定值数组,如果不对其稍加修改,就无法将其存储为文本。
为了解决这个问题,您可以用JSON格式对选定的值数组进行编码,然后存储它。
// in your controller
$values = $request->all();
$values['genetics'] = json_encode($values['genetics']); // replacing the array value to json
Gecko::create($values);而且,要检索返回的值(例如,在视图中填充select时),您可以用相反的json_decode()函数直观地将JSON字符串解码回数组。
注意:确实记得在selects中添加multiple属性,以使用户能够选择多个选项。那是,
<select name="genetics[]" class="form-control" multiple> https://stackoverflow.com/questions/33260112
复制相似问题