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')
->inRandomOrder()
->first();
9. Union querys
$first = DB::table('users')
->whereNull('first_name');
$users = DB::table('users')
->whereNull('last_name')
->union($first)
->get();
10. Join tables
DB::table('users')
->join('contacts', function ($join) {
$join->on('users.id', '=', 'contacts.user_id');
})
->get();
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)