Laravel’s Eloquent ORM is well-known for providing an elegant and straightforward way to interact with databases.
However, it also hides many powerful methods that can make developer’s life easier while building Laravel applications.
In this blog post, we will explore few of these hidden or lesser-known Eloquent features. Each method is explained simply and demonstrated with practical examples to help you understand when and how to use them.
Bulk Insert or Update
The upsert method lets you insert new records or update existing ones in a single command, making data synchronization efficient and reducing database load.
Product::upsert(
[
['sku' => 'A100', 'stock' => 10],
['sku' => 'B200', 'stock' => 5],
],
['sku'],
['stock']
);
As per this example, It will update stock quantities based on unique SKUs. However, there is posiblity that some SKUs does not exists into out products table. Then it will insert those records if needed.
With help of upsert method, we don’t have to explicitly manage insert and update logic seperatly.
Quick Mass Deletion with Destroy
The destroy
method deletes one or more records by their primary keys without loading the models into memory.
This makes destroy
faster and more efficient than calling delete
on individual model instances, especially when you need to remove multiple records at once.
Notification::destroy([11, 32, 45]);
In the example above, multiple notifications are deleted in a single operation. Unlike the delete
method, which requires loading each model instance before deleting and firing associated model events, destroy
directly executes a delete query based on the IDs. This reduces memory usage and decreases execution time.
Clone Existing Record
Replicate creates a copy of a model instance without saving it, enabling duplication for editing or backup purposes.
use App\Models\Post;
$post = Post::find(2);
$newPost = $post->replicate();
$newPost->title = 'Draft: '.$post->title;
$newPost->save();
As you can see above code will copy one post’s content and save it as new cloned record with changing title for that post. Apart from title, Laravel’s replicate will keep all attributes same as primary model.
Compare Model Instances
The is
method checks if two models represent the same record, making identity comparisons simple and clear. The opposite, isNot
, verifies that two models do not represent the same record.
if ($user->is($admin)) {
// Grant special privileges
}
if ($user->isNot($guest)) {
// Restrict certain actions
}
In this example, the first condition confirms if $user
and $admin
are the exact same database record, useful for granting special access.
The second condition uses isNot
to ensure $user
is not the same as $guest
, enabling logic to restrict actions accordingly. These methods helps to avoid manual ID checks, making comparisons cleaner.
Conditional Relationship Loading
LoadMissing loads related data only if it hasn’t been loaded yet, saving unnecessary queries.
$post->loadMissing('comments');
It will load or query database with eager loading only when there is no data for that relationship. With help of loadMissing feature of Laravel Eloquent ORM we can optimize application performance.
Retrieve IDs from Collection
ModelKeys extracts primary keys from a collection for use in further operations.
$userIds = User::where('subscribed', true)->get()->modelKeys();
It collects IDs of subscribed users, handy for batch updates or notifications. It can be also helpful in case of queues.
Filter Collection by IDs
The only narrows down a collection to include only specified items by their primary keys.
$filteredProducts = $products->only([1, 5, 9]);
This helps target a subset of models already loaded into memory, avoiding extra queries.
Control Attribute Visibility
MakeHidden and makeVisible toggle attribute visibility during serialization for privacy or API response customization.
$user->makeHidden(['email', 'phone']);
$user->makeVisible(['email']);
This methods are used to hide sensitive information for regular user and when required it can be visible for few users like admins.
Add Virtual Attributes
Append adds additional accessor-based attributes to the model’s array or JSON form for richer output.
$user->append('full_name');
This includes the computed full name in API responses, enhancing front-end displays.
Safe Batch Processing
ChunkById processes large datasets in chunks to avoid memory issues and script timeouts.
User::chunkById(500, function($users) {
foreach ($users as $user) {
// Send email
}
});
For handling huge data sets can take too much resources of server. With help of Laravel ChunkById can reduce this performance problem. It process small batches of data at a time for performance optimization.
Enforce Single Record
Sole returns exactly one record or throws an exception if there is none or more than one records.
It can be used in processes like unique usernames, email or any other main constraints.
$admin = User::where('role', 'admin')->sole();
As per this example code, It will get admin record if there is only one user with admin role otherwise it will throw error.
Track Field Changes
The getDirty
method returns the attributes that have been changed on a model but not yet saved, useful for logging or conditional updates. Conversely, getOriginal
provides the original values of attributes before any changes, allowing you to compare before and after states.
$user->name = 'Alex';
$changes = $user->getDirty(); // ['name' => 'Alex']
$originalName = $user->getOriginal('name'); // The original name before change
This type of approach can be used to manage editing request to perform some additional operation. For example, If the slug for post is changed then, it can help to identify and perform operations like re-generating sitemaps.
Conclusion
These hidden Laravel Eloquent methods help create more efficient, readable, and powerful database interactions.
Using upsert
simplifies bulk data sync, chunkById
safely handles large datasets, and makeHidden
/ makeVisible
gives flexible control over API data visibility.
By using these features, developers can build applications that are not only easier to maintain but also perform much better under real-world conditions.