1

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?

1
  • 1
    an empty collection would still be evaluated to true so you need another mechanism to check if the collection is empty or not. One is to use isNotEmpty method, as in: ..->id)->get()->isNotEmpty() Or use exists method Refer here: laravel.com/docs/8.x/collections#method-isnotempty Commented Aug 15, 2021 at 4:14

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

@lagbox my bad it was supposed to be calling isEmpty() after calling get(). Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.