DEV Community

Cover image for Tips ORM Laravel that can help you
Diogo Machado
Diogo Machado

Posted on

Tips ORM Laravel that can help you

The Eloquent ORM Laravel is too difference ORM that all others Framework that I used, he really help us are productive work, let's go around a somethings tips that I separated for you.

1. Order by

$items = Item->orderBy('created_at', DESC)->get();
Enter fullscreen mode Exit fullscreen mode

2. Where

$items = Item->where('category_id', $id)->orderBy('created_at', DESC)->get();
Enter fullscreen mode Exit fullscreen mode

3. Where month (Ex.: January)

$items = Item->whereMonth('created_at', '1')->get();
Enter fullscreen mode Exit fullscreen mode

4. Where year

$items = Item->whereYear('created_at', '1999')->get();
Enter fullscreen mode Exit fullscreen mode

5. Where between

$users = DB::table('users')->whereBetween('votes', [1, 100])->get();
Enter fullscreen mode Exit fullscreen mode

You can also use aggregate, sum, max, min, count, avg, for example

6. Aggregate

$users = DB::table('users')->count();
Enter fullscreen mode Exit fullscreen mode

Sometimes, you may not want to select all columns, so, using select method, you can specify the columns you need

7. Select specify columns

$users = DB::table('users')->select('name', 'email as user_email')->get();
Enter fullscreen mode Exit fullscreen mode

8. Select random row

$randomUser = DB::table('users')
                ->inRandomOrder()
                ->first();
Enter fullscreen mode Exit fullscreen mode

9. Union querys

$first = DB::table('users')
            ->whereNull('first_name');

$users = DB::table('users')
            ->whereNull('last_name')
            ->union($first)
            ->get();
Enter fullscreen mode Exit fullscreen mode

10. Join tables

DB::table('users')
        ->join('contacts', function ($join) {
            $join->on('users.id', '=', 'contacts.user_id');
        })
        ->get();
Enter fullscreen mode Exit fullscreen mode

It`s, I hope you like ten tips of Eloquent Power, if you need read more about this topic, check out the documentation of Laravel:

See you later!

Top comments (0)