I select an array with categories via json_decode
and attach them to the article.
public static function setArticleCategory(Request $request) {
$article = Article::where('id', $request->article_id)->first();
if(!$article){
return response()->json([
'message' => 'Article not found'
], 404);
}
$categories_ids = json_decode($request->categories_ids);
$article->categories()->attach($categories_ids);
return response()->json([
'message' => $categories_ids
], 200);
}
The question is, how can I check in categories_ids
, for example, if one of the selected categories does not exist in the array?
CodePudding user response:
The fastest way would be to use count()
$categories_ids = json_decode($request->categories_ids);
if (count($categories_ids) != Category::whereKey($categories_ids)->count()) {
//return error.
}
It would not tell you wich one is the non existing category, but it will trigger an error if at least one of them doesnt exist.
Edit (comment)*
if you want to ignore the non existing IDs, use this
$categories_ids = json_decode($request->categories_ids);
$categoryPK = (new Category())->getKeyName();
$categories_ids = Category::whereKey($categories_ids)->pluck($categoryPK)->toArray();
It will return an array of ids that exists in the database based on the input (you need to check for empty array after that).