public function store(Request $request){ $article = Article::create($request->only(['content'])); $categories = explode(",",$request->get('categories')); $category_ids =[]; foreach ($categories as $category) { $category_db = Category::where('name', trim($category))->firstOrCreate(['name'=> trim($category)]); $category_ids [] = $category_db->id; } $article->category()->attach($category_ids); return response("Successfully Added to Database");}最后沒有逗號(hào)也沒有問題 , 在數(shù)據(jù)庫中一切都很好現(xiàn)在的問題是,當(dāng)我在末尾放一個(gè)逗號(hào)時(shí),數(shù)據(jù)庫中會(huì)創(chuàng)建一個(gè)帶有空格的單元格我知道為什么會(huì)這樣。包含值的分解數(shù)組的最后一個(gè)鍵是空格。但我想省略或留下那個(gè)空鑰匙。我怎樣才能做到這一點(diǎn)?
1 回答

慕俠2389804
TA貢獻(xiàn)1719條經(jīng)驗(yàn) 獲得超6個(gè)贊
您應(yīng)該使用array_filter()
which 將從數(shù)組中刪除所有空鍵。所以這里是你應(yīng)該使用的代碼:
$categories = array_filter(explode(",",$request->get('categories')));
- 1 回答
- 0 關(guān)注
- 132 瀏覽
添加回答
舉報(bào)
0/150
提交
取消