8 interesting functions of Laravel Eloquent (ORM)
Laravel 11-Jul-2022

8 interesting functions of Laravel Eloquent (ORM)

In this article, we’ll try to understand more about 8. Laravel Eloquent functions and explains them

One of the main concerns for developers is the need to create security queries, create complicated queries, speed up development using databases, making it easier to switch between databases and databases. when using databases within their apps.

Laravel utilizes a feature known as Eloquent that solves this problem. Eloquent is an object-relational mapper (ORM) available in the default Laravel framework. Eloquent assists in working with databases by providing an object-oriented way of inserting, updating, and deleting database records in addition to providing a simple interface for performing complicated SQL queries.

In this article, we’ll try to know more about the 8 Laravel Eloquent functions, and also introduce these functions. Put on your seat belts and prepare to go!

1- Replicate

How can you accomplish this when you need to duplicate or replicate the database records? To accomplish the same, Laravel has introduced a function known as Replicate.

With this function, you can use the function to apply any changes you’d like to it and then save it.

If you own a store product that you wish to copy and change the title and save it for publication.

This method of replication is useful for rapidly duplicating or cloning a database record.

$product = Product::find(1);
 
$newProduct = $product->replicate();
$newProduct->created_at = Carbon::now();
 
$newProduct->save();

2- One of Many

Let’s say there’s a User model that has a one-to-many relationship to the post model. Post model. The next step is to select the first and last post for the particular user.

You can make use of latestOfMany as well as the oldestOfMany feature that Laravel gives to accomplish this.

public function latestOrder()
{
  return $this->hasOne(Order::class)->latestOfMany();
}

public function oldestOrder()
{
  return $this->hasOne(Order::class)->oldestOfMany();
}

The function that is the most recent will return the latest post that was sent from the person using it. The oldestPost function returns the oldest post made by the user in accordance with the primary key model. However, you might need to find a record that is subject to specific requirements. For example, if you want to locate the post that has the highest number of visits, try this:

public function largestOrder()
{
  return $this->hasOne(Order::class)->ofMany('price', 'max');
}

Notes: You can also apply a filter to the results by using a closure function.

3- reject

This function can be used to eliminate models based on the specified condition.

For instance, in the following example, we would like to eliminate items priced over 200 dollars from our collection.

$collection = collect([1, 2, 3, 4]);

$filtered = $collection->reject(function ($value, $key) {
  return $value > 2;
});

$filtered->all();
// [1, 2]

4- isDirty

isDirty method identifies if an attribute of the model has changed in the process of retrieving.

It is also possible to pass an attribute or two to this method to see whether any changes have been made.
The function isDirty() function is executed when a model is called and returns a true or false value that has changed but hasn’t changed.

For instance, we have a User model we would like to verify for any modifications.

$user = User::create([
'first_name' => 'Taylor',
'last_name' => 'Otwell',
'title' => 'Developer',
]);
 
$user->title = 'Painter';
 
$user->isDirty(); // true
$user->isDirty('title'); // true
$user->isDirty('first_name'); // false
$user->isDirty(['first_name', 'title']); // true
 
$user->save();

5- truncate

You can use the truncate feature to erase all the data that is associated with the model from the database.

Post::truncate();

The command above will erase all table information that is related to the Post model. Post model!

6- is & isNot

You might need to verify whether the two models are identical. The functions are is and not will do this for you.

if ($post->is($anotherPost)) {
//
}
 
if ($post->isNot($anotherPost)) {
//
}

7- withCount (Count in relation)

You can get numbers of rows within a relation by using the function withCount.

Let’s say you have a user model with an abundance of messages. You can calculate the messages sent by users using the command Count.

Check out this example

$posts = Post::withCount('comments')->get();

foreach ($posts as $post) {
   echo $post->comments_count;
}

8- withWhereHas()

This method is a way to simplify situations that require repeating the code to filter using whereHas and then pick the record by the use with() (This function is available starting with Laravel version 9.16.0 and up)

$posts = Post::whereHas('comments', function (Builder $query) {
$query->where('content', 'like', 'code%');
})->get();
//Using the withWhereHas method, you can simplify your code around this use case:
Post::withWhereHas('products', fn ($query) => $query->where('enabled', true)->where('sale', true));