php - check if the row exists or not in the database -


hi i'm inserting rows in database , , want check if value exists don't insert , if not insert , that's controller :

<?php  namespace app\http\controllers;  use illuminate\http\request;  use app\http\requests; use app\http\controllers\controller; use input; use auth; use app\user; use app\product; use db;  class listcontroller extends controller {     //     public function getindex(request $request){         $user_id=auth::user()->id;         $list=db::table('wishlist')                 ->join('products','wishlist.product_id','=','products.id')                 ->join('users','wishlist.user_id','=','users.id')                 ->select('wishlist.id','wishlist.product_id','wishlist.user_id',                     'products.id p_id','products.name','products.salary','products.image_name',                     'users.id u_id')                 ->where('wishlist.user_id','=',$user_id)                 ->get();          return view('contents.wishlist')->with('list',$list);     }     public function postindex(request $request){         $id=$request->input('id');         $user_id=auth::user()->id;         $product_id =$request['product_id'];           db::table('wishlist')->insert(['id'=>$id,'user_id'=>$user_id,'product_id'=>$product_id]);         return redirect('wishlist');     }     public function deletedeleteproduct(request $request,$id){         $pro=$request->get('id');         db::table('wishlist')->where('id',$pro)->delete();         return redirect('wishlist');     } } 

can me checking if exists or not ?

the answer use count function :

public function postindex(request $request){          $id=$request->input('id');         $user_id=auth::user()->id;         $product_id =$request['product_id'];          $wishlist=db::table('wishlist')                     ->where('user_id','=',$user_id)                     ->where('product_id','=',$product_id)                     ->count();          if($wishlist > 0){             return redirect('wishlist');         }         else{             db::table('wishlist')               ->insert(['id'=>$id,'user_id'=>$user_id,'product_id'=>$product_id]);             return redirect('wishlist');         } } 

Comments

Popular posts from this blog

ruby - Trying to change last to "x"s to 23 -

jquery - Clone last and append item to closest class -

css - Can I use the :after pseudo-element on an input field? -