Laravel Eloquent having() Query Example

laravel eloquent having query example; In this tutorial you will learn how to use eloquent having query in laravel application.

The use of having query in laravel used to same as where clause method. You may pass multiple arguments to the groupBy method to group by multiple columns.

Below the best example for laravel having query.

Example 1: Laravel having() Query

use App\Models\User;

class UserController extends Controller
{
    public function index()
    {
        $users = User::having('salary', '>', 1000)
                    ->get();
    }
}

Example 2: groupBy & having Methods

use App\Models\User;

class UserController extends Controller
{
    public function index()
    {
        $users = User::groupBy('email', 'status')
                    ->having('id', '>', 1)
                    ->get();
    }
}

Example 3: havingBetween  with groupBy

You can use the havingBetween method to filter the results within a given range:

$report = DB::table('orders')
                ->selectRaw('count(id) as number_of_orders, customer_id')
                ->groupBy('customer_id')
                ->havingBetween('number_of_orders', [5, 15])
                ->get();

I hope its works for you…

Leave a Comment