Laravel get count with where condition

You can use count() method after where condition on model to get the number of records of filtered data in laravel.

Answers 2
  • Get count of records after where condition in laravel

    //Code in controller's method
    $query = "john";
    $users = User::where('name','like','%'.$query.'%');
    $usersCount = $users->count();
    echo $usersCount;
    
    //Import user model in controller class
    use App\Models\User;
    
    0

    This code snippet returns the count of records of filtered data after where condition in laravel. You have to pass query which you want to search in name column of user's table and after that use count method to get the count of record. You can pass dynamic value to query variable by passing the input parameter value using form input arrtibute.

  • Count all and get records using pagination after where condition in laravel

    $query = "john";
    $users = User::where('name','like','%'.$query.'%');
    $usersCount = $users->count();
    $users = $users->select('*')->paginate(3);
    echo $usersCount;
    print_r($users);
    
    //Import user model
    use App\Models\User;
    
    0

    You can get the count of all filtered records from users table and get data using pagination in laravel

  • Back to code snippet queries related laravel