Check if row exists, Laravel

后端 未结 4 1083
失恋的感觉
失恋的感觉 2021-02-04 02:13

I have the following db structure:

items:
id, name, user_id

users table:
id, name

user_favorites table:
id, user_id, item_id

On my items perm

4条回答
  •  旧时难觅i
    2021-02-04 02:48

    Let User_favorite be a model that accesses your user_favorites table

    $result = User_favorite::where('user_id',Auth::getUser()->id)
                             ->where('item_id',$item->id)
                             ->first();
    
    if (is_null($result)) {
    // Not favorited - add new
        User_favorite::create(['user_id'=>Auth::getUser()->id,'item_id'=>$item->id]);
    } else {
    // Already favorited - delete the existing
        $result->delete();
    }
    

提交回复
热议问题