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");
}
In the end there is no comma and no issue and in the database everything is fine
Now problem is that when i put a comma in the end there is a cell created in the database with whitespace
I know why this happening. The last key of the exploded array containing value is whitespace. But i want to omit or leave that empty key. How can i do that?
You should use array_filter()
which will remove all empty keys from the array. So here is the code you should use:
$categories = array_filter(explode(",",$request->get('categories')));