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

 

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:

User::latest()->get();

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

User::oldest()->get();

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()
    {
        parent::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)
    ->get();

 

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.

Model:

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()
    ->discounted()
    ->popular()
    ->get();

 

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
Carbon Add Days To Date In Laravel
Carbon Add Days To Date In Lar...

In this article, we will see carbon add days to date in laravel. Carbon provides the addDay() and addDays() functions to...

Read More

Dec-03-2020

Top 12 Tips To Improve React JS Performance In 2023
Top 12 Tips To Improve React J...

In the dynamic world of web development, staying ahead of the curve is essential, and in 2023, React JS continues to be...

Read More

Aug-28-2023

7+ Laravel Tips: Optimize Database Queries (2024)
7+ Laravel Tips: Optimize Data...

Hey there, fellow developers! If you've been navigating the intricate world of Laravel, you know that optimizing dat...

Read More

Jan-03-2024

VPS Servers - Take a Step Ahead to More Growth
VPS Servers - Take a Step Ahea...

It is the poor hosting that is causing you so many issues. If you upgrade to advanced hosting based on your website need...

Read More

Apr-08-2022