12 Hidden Features of Laravel Eloquent

12 Hidden Features of Laravel Eloquent

Laravel Eloquent is a feature-rich ORM (Object Relational Model). You can not find all the features in official documentation of Laravel Eloquent.

I believe, to understand any open source software or framework, you have to spend more time reading the source code.

If you read through the classes which power Laravel Eloquent, you will find many interesting features which can be useful while you developing Laravel based application.

Here are some features that you may not know.

1. Expressive Where Syntax

We can make our where clause more expressive when retrieving a particular record. Ususally when you grab a record, you would do like this:

$product = Product::where('category', 2)->get();

You can make this query more expressive like below, by suffixing the attribute to where clause itself.

$product = Product::whereCategory(2)->get();

2. Returning Relations On Model Save

If we save a model and return the saved model, it only returns the model you are saving. What if, you want to return its related model. You can do like below:

public function store(Request $request, $categoryId)
{
    $product = new Product();
    $product->fill($request->all());
    $product->category_id = $categoryId;

    $product->category; // Set the model to load related model
    // On return it will provide related model
    return $product->save();

3. Specifying Attributes in find() Method

Usually, you find by the model by a primary key like below.

$product = Product::find(1);
// Or
$product = Product::findOrFail(1);

You can specify the attributes to select as a second argument like below.

$product = Product::find(1, ['name', 'sku', 'price']);
// Or
$product = Product::findOrFail(1, ['name', 'sku', 'price']);

4. Increment And Decrement Model Attributes

You can increment or decrement a model attribute using increment() and decrement() methods. Just like below:

// adds one view to product model
Product::find($productId)->increment('views');
// or you can add any number
Product::find($productId)->increment('views', 5);
// Remove one view from producr model
Product::find($productId)->decrement('views');
// or you can add any number
Product::find($productId)->decrement('views', 5);

5. Checking If Models Are Same

You can determine if two models have the same ID and belongs to same database table using is() method.

$product = Product::find(1);
$sameProduct = Product::find(1);
$nextProduct = Product::find(2);
$product->is($sameProduct);       // true
$product->is($nextProduct);       // false

Very handy when you are dealing with a lot of models.

6. Clone A Model

You can replicate or clone a model using replicate() method. It will create a copy of the model into a new, non-existing element.

$product = Product::find(1);
$newProduct = $product->replicate();

$newProduct->save();

7. Checking If Model Has Changed

You can determine if the model or given attributes have been changed using isDirty() method.

$product = Product::first();
$product->isDirty();    // false

$product->name = "Lenove ThinkPad";
$product->isDirty();    // true

You can also pass attributes to check, if they have changed or not.

$product->isDirty('name');      // true
$product->isDirty('price');     // false

8. Get Changed Attributes

If you want to see the changed attributes for a model, you can use getChanges() method. For our above code example, we will get the changed attributes.

$product->getChanges();

Result will be:

[
    'name'  =>  'Lenovo ThinkPad'
]

9. Get Original Attributes

When you are mutating an Eloquent model, you can get the original attributes by using getOriginal() method.

$product = Product::first();
$product->name;     //  Lenovo ThinkPad 2019

$product->name = "Lenovo ThinkPad";     //  Lenovo ThinkPad

$product->getOriginal('name');      //  Lenovo ThinkPad 2019

// Or

$product->getOriginal();

10. Saving Models and Relationships

You can save model and its corresponding relationship using the push() method.

$product = Product::first();
$product->name = "Lenovo ThinkPad";

$product->category->name = "Laptops";
$product->push(); // This will update the product and category models both.

11. Reloading Fresh Model

If you want to reload a fresh instance of the model from the database, you can use fresh() method on the model.

$product = Product::first();
$product->name;     // Lenovo ThinkPad 2018

// Meanwhile, another user updated the record for this model and name changed to "Lenovo ThinkPad 2019"

$freshProduct = $product->fresh();
$freshProduct->name;    // Lenovo ThinkPad 2019

// Your $product instance has old value
$product->name;     // Lenovo ThinkPad 2018

12. Reloading Existing Model

You can also reload the fresh model with fresh values from database, using refresh() method.

$product = Product::first();
$product->name;     // Lenovo ThinkPad 2018

// Meanwhile, another user updated the record for this model and name changed to "Lenovo ThinkPad 2019"

$product->refresh();
$product->name;    // Lenove ThinkPad 2019

That’s all for now. If you like this post or have a suggestion to improve this post, please leave a comment in below comment box.

4 comments on “12 Hidden Features of Laravel Eloquent

Leave a Reply

Your email address will not be published. Required fields are marked *

*

*
*

This site uses Akismet to reduce spam. Learn how your comment data is processed.