Use 𝘄𝗵𝗲𝗿𝗲𝗕𝗲𝘁𝘄𝗲𝗲𝗻 to load records between two timestamps, you can pass the fallback value using the null coalescing operator (??).
// Load tasks completed between two timestamps
Task::whereBetween('completed_at', [
$request->from ?? '2023-01-01',
$request->to ?? today()->toDateTimeString(),
]);
If your DB table doesn't contain timestamp fields created_at
and updated_at
, you can specify that Eloquent model wouldn't use them, with $timestamps = false
property.
class Post extends Model
{
public $timestamps = false;
}
In Eloquent Query Builder, you can specify "as" to return any column with a different name, just like in plain SQL query.
$users = DB::table('users')->select('name', 'email as user_email')->get();
This is a typical way to define a relationship:
public function users() {
return $this->hasMany('App\User');
}
But did you know that at this point we can already add where
or orderBy
? For example, if you want a specific relationship for some type of users, also ordered by email, you can do this:
public function approvedUsers() {
return $this->hasMany('App\User')->where('approved', 1)->orderBy('email');
}
Instead of using the 𝘄𝗵𝗲𝗿𝗲𝗜𝗻() method to load a large range of data when the targeted value is an integer, use 𝘄𝗵𝗲𝗿𝗲𝗜𝗻𝘁𝗲𝗴𝗲𝗿𝗜𝗻𝗥𝗮𝘄() which is faster than 𝘄𝗵𝗲𝗿𝗲𝗜𝗻().
// instead of using whereIn
Post::whereIn('id', range(1, 50))->get();
// use WhereIntegerInRaw method for faster loading
Post::whereIntegerInRaw('id', range(1, 50))->get();
You can use whereColumn
method to compare the values of two columns.
return Post::whereColumn('created_at', 'updated_at')->get();
// pass a comparison operator
return Post::whereColumn('created_at', '>', 'updated_at')->get();
Sometimes we need to load a huge amount of data into memory. For example:
$orders = Order::all();
But this can be slow if we have really huge data, because Laravel prepares objects of the Model class. In such cases, Laravel has a handy function toBase()
$orders = Order::toBase()->get();
//$orders will contain `Illuminate\Support\Collection` with objects `StdClass`.
By calling this method, it will retrieve the data from the database, but it will not instantiate and populate the Model class. It's important to note that it's often a good practice to pass an array of specific fields to the get
method, thereby preventing unnecessary fields from being fetched from the database.
You might also like: