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
Angular 15: Unleashing Modern Web Development
Angular 15: Unleashing Modern...

Angular 15 is the latest iteration of one of the most popular JavaScript frameworks for building dynamic web application...

Read More


How To Remove Spaces Using JQuery
How To Remove Spaces Using JQu...

In this article, we will explain to you how to remove extra space using jquery. many times we have requirements to...

Read More


Laravel 9 REST API With Passport Authentication
Laravel 9 REST API With Passpo...

In this article, we will see an example of laravel 9 REST API with passport authentication. Also, perform CRUD...

Read More


Laravel 11 Livewire Datatable Example
Laravel 11 Livewire Datatable...

Hello, laravel web developers! In this article, we'll see how to create datatable in laravel 11 livewire using medic...

Read More