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();

2. Where

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

3. Where month (Ex.: January)

$items = Item->whereMonth('created_at', '1')->get();

4. Where year

$items = Item->whereYear('created_at', '1999')->get();

5. Where between

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

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

6. Aggregate

$users = DB::table('users')->count();

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();

8. Select random row

$randomUser = DB::table('users')

9. Union querys

$first = DB::table('users')

$users = DB::table('users')

10. Join tables

        ->join('contacts', function ($join) {
            $join->on('', '=', 'contacts.user_id');

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!

Discussion (0)