Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if row exists, Laravel

Tags:

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 permalink pages, I have an 'Add to favorites' button which inserts a new row into user_favorites

I want to be able to replace it for a 'Remove from favorites' button if the user already has it in their favorites.

I can't figure out the logic behind this - do I need to check if a row exists in user_favorites that has the current user's id and the permalink item id? This did not work for me:

if (Auth::user()->id) {     if (!is_null(DB::table('user_favorites')->where('user_id', '=', Auth::user()->id)->where('item_id', '=', $item->id)->first())) {         // remove from favorites button will show     } } 
like image 653
O P Avatar asked Aug 08 '14 17:08

O P


People also ask

How to check record exists in Laravel?

The efficient way to check if the record exists you must use is_null method to check against the query. The code below might be helpful: $user = User::where('email', '=', Input::get('email')); if(is_null($user)){ //user does not exist... }else{ //user exists... }

What is the method used to identify if a record is existing or not?

First, we check if the record exists with the EXISTS keyword. EXISTS executes the query we tell it to (the SELECT ) and returns a boolean value. If it finds the record, we return 'This record already exists!' to our recordset and do nothing else.

How do I know if a table is empty in laravel?

You can call eloquent count function to get count and then check if count is equal to zero. if($collection->isEmpty()){ //products table is empty. }


1 Answers

You may want something like this:

$user_favorites = DB::table('user_favorites')     ->where('user_id', '=', Auth::user()->id)     ->where('item_id', '=', $item->id)     ->first();  if (is_null($user_favorites)) {     // It does not exist - add to favorites button will show } else {     // It exists - remove from favorites button will show } 
like image 156
Simone Avatar answered Oct 20 '22 19:10

Simone