简体   繁体   中英

Check if value exists in database or not in laravel

I have wishlist system where i save user_id and product_id and i want to check before save into wishlist table to see if user already saved this product in there or not.

I found some question and articles about this but all of them only validate 1 value and not both, what I need is to check auth::user()->id and product->id both before saving.

here is my store method:

  public function store(Request $request)
    {
      //Validating title and body field
      $this->validate($request, array(
          'user_id'=>'required',
          'product_id' =>'required',
        ));

      $wishlist = new Wishlist;

      $wishlist->user_id = $request->user_id;
      $wishlist->product_id = $request->product_id;


      $wishlist->save();

      return redirect()->back()->with('flash_message',
          'Item, '. $wishlist->product->title.' Added to your wishlist.');
    }

this is my form:

<form action="{{route('wishlist.store')}}" method="post">
                                    {{csrf_field()}}
                                    <input type="text" name="user_id" value="{{Auth::user()->id}}" hidden>
                                    <input type="text" name="product_id" value="{{$pdts->id}}" hidden>
                                    <button type="submit" class="btn btn-success">
                                        <i class="fa fa-heart"></i>
                                    </button>
                                  </form>

thanks.

You could use firstOrCreate() and forget about validating the composite key.

public function store(Request $request)
{
    $data = $request->validate([
        'user_id'    => 'required',
        'product_id' => 'required'
    ]);

    $wishlist = Wishlist::firstOrCreate($data);

    return redirect()
        ->back()
        ->with('flash_message', 'Item, ' . $wishlist->product->title . ' added to your wishlist.');
}

The firstOrCreate() method will try to find a record from your wishlists table with the given data and, in case it didn't find any, it will create a new one and return it.

In other words, if it can't find a record with the given user_id and product_id values, it will create a new one.

Or you could register acustom validation rule like you have been already suggested.

You could use the isset function to check whether the property is set or not

public function store (Request $request)
{

          // backend validator goes code here
          $status=Wishlist::where('user_id',Auth::user()->id)
                                           ->where('product_id',$request->product_id)
                                           ->first();

           if(isset($status->user_id) and      isset($request->product_id))
           {
                  //Return to already added page
           }
          else
          {
                  //Return to successfully added page
          }

}

I think the best way for performing this, is to make a new rule.

You can run this command: php artisan make:rule NameOfRule

then write your logic through NameOfRule class's passed method the file will be located under 'App\Rules' folder.

For example :

   public function passes($attribute, $value)
    {
        return User::where(' add your wheres if needed')->exist();
    }

After this you can call your self rule as new instance. For example :

$request->validate(['name'=>[new NameOfRule]]);

'email' => "必需|email|存在:用户、email、email、$request->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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM