YouTube Icon

Code Playground.

How to use Ordering, Grouping, Limit, & Offset in Laravel 5

CFG

How to use Ordering, Grouping, Limit, & Offset in Laravel 5

For sort the result-set in ascending or descending order, the orderBy method is used. The first argument for the orderBy approach should be the column by which you want to sort, whereas the second argument governs the sort path and can either be asc or desc.

$order = DB::table('tbl_order')
        ->orderBy('id', 'desc')
        ->get();
$order = DB::table('tbl_order')
        ->orderBy('id', 'asc')
        ->get();

latest / oldest

The latest and oldest methods allow you to easily order results by date. By default, result will be ordered by the created_at column. Or, you can pass specific column name wise sort.

$order = DB::table('tbl_order')
                ->latest()
                ->first();
$order = DB::table('tbl_order')
                ->oldest()
                ->first();

inRandomOrder

The inRandomOrder method may be used to sort the query results randomly.

$order = DB::table('tbl_order')
                ->inRandomOrder()
                ->first();

groupBy / having / havingRaw

The groupBy and having methods may be used to group the query results. The having method's same as where method.

$order = DB::table('tbl_order')
                ->groupBy('user_id')
                ->having('amount', '>', 100)
                ->get();

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

$order = DB::table('tbl_order')
                ->select('user_id', DB::raw('SUM(amount) as total_sales'))
                ->groupBy('user_id')
                ->havingRaw('SUM(amount) > 2500')
                ->get();

skip / take

To limit the number of results returned from the query, or to skip a given number of results in the query.

$order = DB::table('tbl_order')->skip(8)->take(4)->get();

You may use the limit and offset methods.

$order = DB::table('tbl_order')
                ->offset(8)
                ->limit(4)
                ->get();




CFG