Laravel tips DB Models and Eloquent - Part 3

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

Welcome back to the third installment of our series on Laravel tips for database models and Eloquent. If you've been following along from the beginning, you're already well-acquainted with the power and flexibility that Laravel's database layer brings to your applications.

If you're just joining us, don't worry—there's plenty of knowledge ahead that you can leverage to supercharge your Laravel development journey. In our previous parts, we've covered a wide range of topics, from fundamental model setup to advanced querying techniques.

In Part 3, we'll continue to explore the world of Laravel's Eloquent ORM and database modeling. These tips are designed to help you not only master the art of efficient database design but also to harness the full potential of Eloquent, Laravel's eloquent query builder.

As we delve deeper into this journey, you'll discover tips and best practices that will elevate your Laravel skills to the next level.

So let's see Laravel Tips DB Models and Eloquent - part 3, Laravel 9/10 Tips, laravel 9/10 Tricks, Laravel DB, laravel Model, Eloquent Laravel, Laravel new Tips and Tricks, Laravel Tips and Tricks 2023.

1. Model all: columns

When calling Eloquent's Model::all(), you can specify which columns to return.

$users = User::all(['id', 'name', 'email']);


2. To Fail or not to Fail

In addition to findOrFail(), there's also Eloquent method firstOrFail() which will return 404 page if no records for query are found.

The findOrFail method in Laravel is a powerful tool when it comes to retrieving records from your database. It's commonly used to fetch a specific record by its primary key and throw an exception if the record is not found.

$user = User::where('email', '[email protected]')->firstOrFail();


3. Column name change

Laravel's Eloquent Query Builder, you can use the as method to specify an alias for a column, just like you would in a plain SQL query. This feature is particularly useful when you need to rename a column for readability, and consistency, or when dealing with calculated values. Here's how you can use it:

$results = DB::table('users')
    ->select('email as user_email')


4. Map query results

After executing an Eloquent query, you can modify the retrieved rows by using the map() function on the resulting collection.

$users = User::where('role_id', 1)->get()->map(function (User $user) {
    $user->some_column = some_function($user);
    return $user;


5. Change Default Timestamp Fields

By default, Laravel assumes that your database table has created_at and updated_at columns for timestamp tracking. However, you can customize these field names on a per-model basis using the $createdAt and $updatedAt properties in your Eloquent model.

class User extends Model
    // Specify custom field names for timestamps
    const CREATED_AT = 'custom_created_at';
    const UPDATED_AT = 'custom_updated_at';



6. Quick Order by created_at

In Laravel, you can easily retrieve records from your database ordered by the created_at column in ascending or descending order using the orderBy method. Here's how to do it:

Instead of:

$records = User::orderBy('created_at', 'desc')->get();

You can do it:


There is an opposite method oldest() which would order by created_at ascending:


Additionally, you can specify another column to order by. For example, if you want to use updated_at, you can do so like this:

$lastUpdatedUser = User::latest('updated_at')->first();


7. Automatic Column Value When Creating Records

If you want to generate a database column value when creating a record, you can add this logic to the model's boot() method. For instance, if you have a field named 'position' and wish to assign the next available position to a new record, such as Country::max('position') + 1, you can achieve it like this:

class Country extends Model {
    protected static function boot()
        Country::creating(function($model) {
            $model->position = Country::max('position') + 1;


8. DB Raw Query Calculations Run Faster

To leverage SQL raw queries, such as the whereRaw() method, you can perform database-specific calculations directly within your query. This approach can often yield faster results. For instance, if you need to retrieve users who have been active for 30 or more days since their registration, consider using the following code as an example:

User::where('active', 1)
    ->whereRaw('TIMESTAMPDIFF(DAY, created_at, updated_at) > ?', 30)


9. More than One Scope

In Eloquent, you have the flexibility to combine and chain multiple query scopes together, allowing you to use more than one scope in a single query. This feature enables you to construct complex queries while keeping your code organized and maintainable.


class Product extends Model
    // Scope to retrieve active products
    public function scopeActive($query)
        return $query->where('status', 'active');

    // Scope to retrieve discounted products
    public function scopeDiscounted($query)
        return $query->where('discounted', true);

    // Scope to order products by popularity (assuming you have a 'popularity' column)
    public function scopePopular($query)
        return $query->orderBy('popularity', 'desc');

Now, you can use these scopes to build your query:

$products = Product::active()


10. No Need to Convert Carbon

When using whereDate() to filter records for today, you can utilize Carbon's now() method, and it will automatically be transformed into a date. There's no need to explicitly call ->toDateString().

// Instead of
$todayUsers = User::whereDate('created_at', now()->toDateString())->get();

// No need to convert, just use now()
$todayUsers = User::whereDate('created_at', now())->get();


You might also like:

Recommended Post
Featured Post
How To Reset Modal Form In jQuery
How To Reset Modal Form In jQu...

Have you ever seen those pop-up boxes on websites? They're called modal forms, and they make it easier to do things...

Read More


Line Breaks In Laravel Blade
Line Breaks In Laravel Blade

In this post, I will show you how to break lines for Textarea in laravel blade. Many times when you save...

Read More


Laravel 9 Livewire Datatable Example
Laravel 9 Livewire Datatable E...

In this article, we will see the laravel 9 livewire datatable example. Here, we will learn how to use livewire data...

Read More


How To Add Datepicker In Angular 15 Material
How To Add Datepicker In Angul...

In this tutorial, I will guide you through the process of adding a datepicker component to your Angular 15 application u...

Read More