我试图保存到我的数据库复选框我检查到我的视图。我有一个title
,一个type_article
(下拉框),theme
(复选框)和contents
。
我在article_list.blade.view
:
@foreach ($themes as $theme)
<div class="form-check form-check-inline">
<input class="form-check-input" type="checkbox" name="themeCheckbox[]" value="{{ $theme->theme_id }}">
<label class="form-check-label">{{ $theme->nom_theme }}</label>
</div>
@endforeach
My AdminController
:
public function createArticle(Request $request)
{
$data = $request->validate([ // $data = $this->validate($request
'titreArticle' => 'bail|required|between:5,40',
'typeArticle' => 'bail|required',
'themeCheckbox' => 'required|array|min:1',
'themeCheckbox.*' => 'required|string|distinct|exists:theme,nom_theme',
'contenuArticle' => 'bail|required',
]);
$type_articles = Type_article::findOrFail($data['typeArticle']);
$article = new Article();
$article->type_article()->associate($type_articles);
$themes = Theme::whereIn('nom_theme', $data['themeCheckbox'])->get();
$article->theme()->associate($themes);
$article->titre = $data['titreArticle'];
$article->contenu = $data['contenuArticle'];
$article->date_creation = date('Y-m-d');
$article->save();
$article->theme()->attach($themes);
return view('admin/panel_admin/panel_admin');
}
一切都很好,除了复选框的问题。我确实在我的视图中显示了我的错误,这是当我提交3个复选框时出现的:
The selected themeCheckbox.0 is invalid.
The selected themeCheckbox.1 is invalid.
The selected themeCheckbox.2 is invalid.
我有一个数据透视表(Article和Theme为表,Article_theme为数据透视表)。
编辑:
问题是$themes = Theme::whereIn('nom_theme', $data['themeCheckbox'])->get();
,我需要将nom_theme
更改为id_theme
。
您应该将$theme->theme_id
传递给复选框的名称数组。然后,检查数组中是否存在id,因为复选框的默认行为是删除未选中的项。
<input class="form-check-input" type="checkbox" name="themeCheckbox[{{$theme->theme_id}}]" value="1">
我将复选框的值设置为1,这意味着当你选中它时,$theme->theme_id
的键值将被赋值为1。该复选框的示例输出如下所示:
themeCheckbox=[
'1' => '1';
'2' => '1';
'3' => '1';
'4' => '1';
'5' => '1';
];
因此,您必须在代码中查找键,而不是值,因为它们是唯一的(1)。如下所示修改控制器并在其中使用array_keys()
方法:
$themes = Theme::whereIn('nom_theme', array_keys($data['themeCheckbox']))->get();
更新删除不必要的验证'themeCheckbox' => 'required|array|min:1',
,并修复另一个,如下所示:
'themeCheckbox.*' => 'required',