【发布时间】:2021-01-15 21:16:59
【问题描述】:
我正在尝试将我在视图中选中的复选框保存到我的数据库中。我有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
我的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。
【问题讨论】: