Reputation: 185
i want to make website which has 'like' and 'dislike'
i made controller
public function addLike($id)
{
$feeling = new Feeling();
$feeling->post_id = $id;
$feeling->user_id = Auth::user()->id;
$feeling->like = 1;
$feeling->check = 1;
if ($dd = DB::table('feelings')->where('post_id', $feeling->post_id)->where('user_id', Auth::user()->id)->get()) {
dd($dd);
return redirect()->route('post.show', ['feeling' => $feeling, 'id' => $id]);
} else {
$feeling->save();
return redirect()->route('post.show', ['feeling' => $feeling, 'id' => $id]);
}
}
i thought if(feeling is $feeling = new Feeling
, and Feeling is my like,dislike model)
when feeling's post number and user number exist on feelings table,
i just return redirect
else, if post number and user number both doesn't exist together i want to save and direct
but i have problem ->>> when post number and user number both doesn't exist together, i checked my web doesn't work properly so i put dd($dd), and saw
Illuminate\Support\Collection {#360 ▼
#items: []
}
$dd = DB::table('feelings')->where('post_id', $feeling->post_id)->where('user_id', Auth::user()->id)
dd($dd)
had made this kind of empty array.
how can i check feeling's post number and user number's existence?
Upvotes: 1
Views: 115
Reputation: 2271
An empty collection would still be evaluated as true
inside the if statement. There are different ways to check for the existence of records in Larave.
One is exists()
$exists = DB::table('feelings')->where('post_id', $feeling->post_id)->where('user_id', Auth::user()->id)->exists();
//$exists returns true is record exists, otherwise false
Check if record collections is empty or not using isEmpty()
or isNotEmpty()
:
$empty = DB::table('feelings')->where('post_id', $feeling->post_id)->where('user_id', Auth::user()->id)->get()->isEmpty();
//$empty returns true if no result
Refer here to check available methods: https://laravel.com/docs/8.x/collections
Upvotes: 1