I want to create a functionality on Laravel that would check the rows of a database table for existence. After checking, depending on the results of the check, it should delete, add new columns or skip them.
foreach($this->category_product as $k => $item) {
$category_product = CategoryProduct::where([['category_id', $this->category_id],['product_id', $k]])->firstOr(function () {
$category_product = CategoryProduct::create([
'category_id' => $this->category_id,
'product_id' => $k
]);
});
}
Here's what I have so far. How to remove rows that do not exist in a query? Any help would be appreciated. Thanks
CodePudding user response:
I hope I understood you right, as the question isn't clear enough, but here is a way to delete the rows if they exist:
Note: you were missing use ($k)
foreach ($this->category_product as $k => $item) {
$category_product = CategoryProduct::where([
['category_id', $this->category_id],
['product_id', $k]
])->firstOr(function () use ($k) {
// Delete if it exists.
CategoryProduct::where([
'category_id' => $this->category_id,
'product_id' => $k
])->delete();
// Create if it doesn't exist.
$category_product = CategoryProduct::create([
'category_id' => $this->category_id,
'product_id' => $k
]);
});
}