Eloquent Where Date Methods
In Eloquent, you can check the date with functions whereDay()
, whereMonth()
, whereYear()
, whereDate()
, and whereTime()
.
$products = Product::whereDate('created_at', '2023-01-31')->get();
$products = Product::whereMonth('created_at', '12')->get();
$products = Product::whereDay('created_at', '31')->get();
$products = Product::whereYear('created_at', date('Y'))->get();
$products = Product::whereTime('created_at', '=', '14:13:58')->get();
Model All Columns
When calling Eloquent's Model::all()
, you can specify which columns to return.
$users = User::all(['id', 'name', 'email']);
DB Transactions
When performing two database operations, if the second operation encounters an error, the first operation should be rolled back. To achieve this, we use database transactions. Transactions ensure that the first operation is automatically rolled back if the second operation fails.
DB::transaction(function () {
DB::table('users')->update(['votes' => 1]);
DB::table('posts')->delete();
});
Eager Loading with Exact Columns
You can use Laravel Eager Loading to retrieve related data along with the main query and specify the exact columns you want to get from the relationship. To optimize performance, you can specify the exact columns you want to retrieve from the related data, rather than retrieving all columns.
$users = Book::with('author:id,name')->get();
You can do that even in deeper, second-level relationships:
$users = Book::with('author.country:id,name')->get();
A Shorter Way to Write WhereHas
Released in Laravel 8.57, here's a shorter way to write whereHas()
with a simple condition inside.
// Before
User::whereHas('posts', function ($query) {
$query->where('published_at', '>', now());
})->get();
// After
User::whereRelation('posts', 'published_at', '>',
See You in next laravel tips & tricks ✌️