Laravel tips: DB Models and Eloquent

Websolutionstuff | Oct-11-2023 | Categories : Laravel MySQL

In the realm of web development, an efficient and robust data handling mechanism is paramount. Laravel, a PHP web application framework, brings the power of Eloquent ORM (Object-Relational Mapping) to the forefront.

Eloquent simplifies database operations, allowing developers to interact with databases using eloquent, expressive syntax.

In this article, we embark on a journey into the world of Laravel's Eloquent ORM, uncovering a treasure trove of tips and techniques that will empower you to wield database models with precision and finesse.

So, let's see laravel tips: db models and eloquent, 10 laravel eloquent tips and tricks.

Eloquent ORM seems like a simple mechanism, but under the hood, there are a lot of semi-hidden functions and less-known ways to achieve more with it. In this article, I will show you a few tricks.

1. Pass a raw query to order your results

You can pass a raw query to order your results. 

For example, sorting tasks by how long before the due date they were completed.

// Sort tasks by the task was completed before the due date

$tasks = Task::query()
    ->whereNotNull('completed_at')
    ->orderByRaw('due_at - completed_at DESC')
    ->get();

 

2. Increments and Decrements

You can increment and decrement using the laravel function instead of the increment operator.

Instead of this:

$article = Article::find($article_id);
$article->read_count++;
$article->save();

You can do this:

$article = Article::find($article_id);
$article->increment('read_count');

Also, these will work:

Article::find($article_id)->increment('read_count');
Article::find($article_id)->increment('read_count', 10); // +10
Product::find($produce_id)->decrement('stock'); // -1

 

3. WhereX

There’s an elegant way to turn this:

$users = User::where('approved', 1)->get();

Into this:

$users = User::whereApproved(1)->get();

 Yes, you can change the name of any field and append it as a suffix to “where” and it will work by magic.

 

4. Load data completed between two timestamps

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(),
]);

 

5. No timestamp columns

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

 

6. Column name change

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

 

7. Relationship with conditions and ordering

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

 

8. Load data faster when the targeted value is an integer

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

 

9. Compare the values of two columns

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

 

10. Reduce Memory

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:

Recommended Post
Featured Post
How to Create Apexcharts Bar Chart in Laravel 11
How to Create Apexcharts Bar C...

Hello developers! In this article, we'll see how to create apexcharts bar chart in laravel 11. ApexCharts is a...

Read More

Apr-17-2024

Carbon Add Months To Date In Laravel
Carbon Add Months To Date In L...

In this article, we will see an example of carbon add months to date in laravel. Here, we will give you a simple&nb...

Read More

Dec-05-2020

Laravel whereBetween Query Example
Laravel whereBetween Query Exa...

In this article, we will see laravel whereBetween query example. SQL provides many different types of methods or qu...

Read More

Jan-13-2021

Laravel 8 Socialite Login with Google Account
Laravel 8 Socialite Login with...

In this article, we will see laravel 8 socialite login with a google account. This post gives you an example of a larave...

Read More

Dec-01-2020