Laravel Database Ordering, Grouping, Limit, & Offset


Laravel Database Ordering, Grouping, Limit, & Offset – The Laravel Database Ordering, Grouping, Limit, & Offset is mostly used to sort the result to the query.


Laravel Database Ordering, Grouping, Limit, & Offset.

Let us understand how to use Laravel Database Ordering, Grouping, Limit, & Offset.

Function:-

There are some followings function available in Laravel Database Ordering, Grouping, Limit, & Offset.

orderBy

The orderBy method allows you to sort the result. The first argument to the orderBy method should be the column which you want to sort. The second argument is asc and desc order.

$users = DB::table('users')
                ->orderBy('name', 'desc')
                ->get();

latest / oldest

The latest and oldest method allow you to order result by date. Result will be ordered by the created_at column.

$user = DB::table('users')
                ->latest()
                ->first();

inRandomOrder

The inRandomOrder method can be used to sort the query result randomly.

$randomUser = DB::table('users')
                ->inRandomOrder()
                ->first();

groupBy / having / havingRaw

The groupBy and having method can be used to group the query result. The having method’s signature is similar to that of the where method.

$users = DB::table('users')
                ->groupBy('account_id')
                ->having('account_id', '>', 100)
                ->get();

The havingRaw method can be used to set a raw string as the value of the having clause.

Let’s look at a simple example.

$users = DB::table('orders')
                ->select('department', DB::raw('SUM(price) as total_sales'))
                ->groupBy('department')
                ->havingRaw('SUM(price) > 2500')
                ->get();

skip / take

To set limit the number of result return from the query or to skip a given number of result in the query. You can use skip and take method.

$users = DB::table('users')->skip(10)->take(5)->get();

You can also use the limit and offset method.

$users = DB::table('users')
                ->offset(10)
                ->limit(5)
                ->get();

Advertisements

Add Comment

📖 Read More