• Home
  • PHP
  • MySQL
  • Demos
  • HTML
  • CSS
  • jQuery
  • Framework
  • Social
  • Request Tutorial
PHP Lift
  • Home
  • Demos
  • Advertisement
PHP Lift
  • Home
  • PHP
  • MySQL
  • Demos
  • HTML
  • CSS
  • jQuery
  • Framework
  • Social
  • Request Tutorial
  • Follow
    • Facebook
    • Twitter
    • Google+
    • Pinterest
    • Youtube
    • Instagram
    • RSS
8 interesting functions of Laravel Eloquent (ORM)
Home
PHP

8 interesting functions of Laravel Eloquent (ORM)

July 9th, 2022 Huzoor Bux PHP 0 comments

Facebook Twitter Google+ LinkedIn Pinterest

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.

Read Also: 6 Reasons Laravel is the Top PHP Framework in the Web Development Industry

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));

Share this:

  • Click to share on Twitter (Opens in new window)
  • Click to share on Facebook (Opens in new window)

Related

  • Tags
  • laravel
  • Laravel Eloquent
  • Laravel ORM
Facebook Twitter Google+ LinkedIn Pinterest
Next article Is PHP dead in 2021? Is PHP still relevant or worth the effort?
Previous article Javascript let vs var

Huzoor Bux

I am a PHP Developer

Related Posts

Is PHP dead in 2021? Is PHP still relevant or worth the effort? PHP
July 10th, 2022

Is PHP dead in 2021? Is PHP still relevant or worth the effort?

How to Extract Text from PDF using PHP PHP
July 3rd, 2022

How to Extract Text from PDF using PHP

How to Create PDFs from HTML with PHP and Dompdf HTML
June 29th, 2022

How to Create PDFs from HTML with PHP and Dompdf

Leave a Reply Cancel reply

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

    Advertisement
    Like us
    Recent Posts
    • Best 10 Programming Languages that will rule in 2022
    • Top 7 Websites To Get Your First Paid Internship
    • How to Create Bar Chart Race in JavaScript
    • 9 Tricks and Tips to Search Google Like a Pro
    • Is PHP dead in 2021? Is PHP still relevant or worth the effort?
    Categories
    • API
    • Bootstrap
    • Bot
    • CSS
    • CSS 3
    • Database
    • Designing
    • Framework
    • Guide
    • HTML
    • HTML 5
    • JavaScript
    • jQuery
    • MySQL
    • Node.js
    • oAuth
    • Payment
    • PHP
    • Python
    • Social
    • Tips
    • WordPress
    Weekly Tags
    • PHP
    • How to
    • javascript
    • api
    • MYSQL
    • laravel
    • jQuery
    • HTML to PDF
    • PHP Basics
    • Programming Habits
    • About
    • Privacy Policy
    • Back to top
    © PHPLift 2021. All rights reserved.