I'm creating a wishlist where the user can save his own products and save them. What I want is that a user can't save a product more than one time. So, what I'm doing is, if the product_id exists in the DB, I don't want to save the new record.
This is my code, what am I doing wrong?
public function addWishlist(Wishlist $wishlist) {
$wishlist->user_id = request('user_id');
$wishlist->product_id = request('product_id');
if(DB::table('wishlists')->where('product_id' !== $wishlist->product_id)) {
$wishlist->save();
return redirect()->back();
}
}
what about this
public function addWishlist(Wishlist $wishlist) {
$userId = request('user_id');
$productId = request('product_id');
$found = Wishlist::where('user_id', $userId)->where('product_id', $productId)->count();
if($found == 0) {
$wishlist->user_id = $userId;
$wishlist->product_id = $productId;
$wishlist->save();
return redirect()->back();
}
}
public function addWishlist(Wishlist $wishlist) {
if(DB::table('wishlists')->where(['user_id'=>$user_id,'product_id'=>$wishlist->product_id])->exists()){
// record already exist
return redirect()->back();
}else{
// record not exist , save the record
$withlist = new Wishlist();
$wishlist->user_id = request('user_id');
$wishlist->product_id = request('product_id');
$wishlist->save();
return redirect()->back();
}
}
You can use firstOrNew
and you need to check with user_id
and product_id
combination
$wishlist::firstOrNew(array('user_id' => request('user_id'),'product_id'=>request('product_id')));
$wishlist->user_id = request('user_id');
$wishlist->product_id = request('product_id');
$wishlist->save();
return redirect()->back();
您是否尝试过FirstOrCreate()
$user = User::firstOrCreate(['email' => $email])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.