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 Upload File on the FTP Server Using PHP
How to Upload File on the FTP...

In this small post i will show you how to upload file on the ftp server using php. As we know there are many ftp functio...

Read More

May-20-2021

How To Integrate Razorpay Payment Gateway In Laravel 9
How To Integrate Razorpay Paym...

In this article, we see how to integrate razorpay payment gateway in laravel 9. As you all know if you are developi...

Read More

Apr-11-2022

How To Image Upload In CKeditor With Laravel 10
How To Image Upload In CKedito...

In this article, we will see how to image upload in CKEditor with laravel 10. Here, we will learn about image uploa...

Read More

May-08-2023

jQuery Datatable Hide/Show Column Based On Condition
jQuery Datatable Hide/Show Col...

In this article, we will see a jquery datatable hide/show column based on condition. Here, we will learn how to hide and...

Read More

Jan-26-2023