Laravel tips DB Models and Eloquent - Part 5

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

Welcome to the fifth installment of our ongoing series, "Laravel Tips: DB Models and Eloquent." In this latest chapter, we continue our exploration of Laravel's powerful Eloquent ORM and database models.

By now, you've likely come to appreciate the elegance and efficiency that Eloquent brings to your Laravel applications, and in this article, we delve even deeper into its advanced capabilities.

Laravel's Eloquent ORM is more than just an object-relational mapper; it's a vital tool for building robust, maintainable, and efficient applications. With each installment of this series.

So, let's see Laravel Tips DB Models and Eloquent - Part 5, Laravel 10 Tips and Tricks, Laravel DB Query, Laravel 10 Eloquent Model, Use DB Transactions, Update or Create, Laravel Query Optimization 2023, Storing Array Type into JSON.

1. Good Old SQL Query

If you need to execute a straightforward SQL query without expecting any results, such as making changes to the database schema, you can use DB::statement().

DB::statement('DROP TABLE users');
DB::statement('ALTER TABLE articles AUTO_INCREMENT=123');

 

2. Use DB Transactions

If you have two database operations to perform, and the second one may result in an error, it's a good practice to use database transactions to ensure data integrity. If the second operation encounters an error, you can then roll back the entire set of changes, including the first operation, to maintain a consistent database state.

Laravel makes it easy to work with database transactions. You can wrap your code in a transaction using the DB::transaction method. Here's an example of how it can be used.

DB::transaction(function () {
    // Perform the first operation
    // Perform the second operation

    // If an exception is thrown, the transaction will be rolled back
});

 

3. Update or Create

If you need to check if a record exists and then update it, or create a new record if it doesn't exist, you can achieve this in a single step using the Eloquent method updateOrCreate(). This method simplifies the process of updating or creating records based on certain conditions, making your code more concise and efficient.

// Instead of this
$flight = Flight::where('departure', 'India')
    ->where('destination', 'Dubai')
    ->first();
if ($flight) {
    $flight->update(['price' => 9900, 'discounted' => 100]);
} else {
    $flight = Flight::create([
        'departure' => 'India',
        'destination' => 'Dubai',
        'price' => 9900,
        'discounted' => 100
    ]);
}
// Do it in ONE sentence
$flight = Flight::updateOrCreate(
    ['departure' => 'India', 'destination' => 'Dubai'],
    ['price' => 9900, 'discounted' => 100]
);

 

4. Forget Cache on Save

If you have a cache key like 'posts' that stores a collection, and you want to clear that cache key when storing or updating new data, you can call the static saved function on your model.

class Post extends Model
{
    // Forget cache key on storing or updating
    public static function boot()
    {
        parent::boot();
        static::saved(function () {
           Cache::forget('posts');
        });
    }
}

 

 

5. Change Format Of Created_at and Updated_at

To modify the format of the created_at timestamp, you can create a method in your model like this.

protected function createdAtFormatted(): Attribute
{
    return Attribute::make(
        get: fn ($value, $attributes) => $attributes['created_at']->format('H:i d, M Y'),
    );
}

Laravel 8:

public function getCreatedAtFormattedAttribute()
{
   return $this->created_at->format('H:i d, M Y');
}

 

6. Storing Array Type into JSON

When you need to store an input field, which is in the form of an array, as JSON in your database, you can make use of Laravel's $casts property within your model.

protected $casts = [
    'images' => 'array',
];

So you can store it as a JSON, but when retrieved from DB, it can be used as an array.

 

7. Make a Copy of the Model

When you have two closely related models, such as a shipping address and a billing address, and you need to duplicate one model into another while making some modifications, you can leverage Laravel's replicate() method.

This method allows you to create a copy of the original model, which you can then customize as needed. It simplifies the process of creating similar records with slight variations.

Example from the official docs:

use App\Models\Address;
 
$shipping = Address::create([
    'type' => 'shipping',
    'line_1' => '123 Example Street',
    'city' => 'Victorville',
    'state' => 'CA',
    'postcode' => '90001',
]);
 
$billing = $shipping->replicate()->fill([
    'type' => 'billing'
]);
 
$billing->save();

 

8. 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`.

 

9. Force query without $fillable/$guarded

When you create a Laravel boilerplate or starter for other developers, and you're uncertain about what fields they will later define in the $fillable or $guarded properties of the model, you can use the forceFill() method.

forceFill() allows you to mass-assign attributes to a model without any regard to the $fillable or $guarded properties. This can be useful in situations where you want to provide flexibility to developers using your starter code, allowing them to set attributes without restrictions.

$team->update(['name' => $request->name])

What if "name" is not in the Team model's $fillable? Or what if there's no $fillable/$guarded at all?

$team->forceFill(['name' => $request->name])

This will "ignore" the $fillable for that one query and will execute no matter what.

 

10. 3-level structure of parent-children

If you have a 3-level structure of parent-children, like categories in an e-shop, and you want to show the number of products on the third level, you can use with('yyy.yyy') and then add withCount() as a condition.

class HomeController extend Controller
{
    public function index()
    {
        $categories = Category::query()
            ->whereNull('category_id')
            ->with(['subcategories.subcategories' => function($query) {
                $query->withCount('products');
            }])->get();
    }
}
class Category extends Model
{
    public function subcategories()
    {
        return $this->hasMany(Category::class);
    }
 
    public function products()
    {
        return $this->hasMany(Product::class);
    }
}
<ul>
    @foreach($categories as $category)
        <li>
            {{ $category->name }}
            @if ($category->subcategories)
                <ul>
                @foreach($category->subcategories as $subcategory)
                    <li>
                        {{ $subcategory->name }}
                        @if ($subcategory->subcategories)
                            <ul>
                                @foreach ($subcategory->subcategories as $subcategory)
                                    <li>{{ $subcategory->name }} ({{ $subcategory->product_count }})</li>
                                @endforeach
                            </ul>
                        @endif
                    </li>
                @endforeach
                </ul>
            @endif
        </li>
    @endforeach
</ul>

 


You might also like:

Recommended Post
Featured Post
Change Text Color Based On Background Color Using Javascript
Change Text Color Based On Bac...

In this article, we will see a change text color based on background color using javascript. Sometimes we have requ...

Read More

Dec-25-2020

Laravel 9 Livewire Dependent Dropdown
Laravel 9 Livewire Dependent D...

In this article, we will see the laravel 9 livewire dependent dropdown. Here, we will learn how to create a dependent dr...

Read More

Nov-29-2022

How to Format Number with 2 Decimal in PHP
How to Format Number with 2 De...

Hey there! If you've ever needed to work with numbers in PHP, you probably know how important it is to format them p...

Read More

Feb-26-2024

Laravel 8 Image Upload Example
Laravel 8 Image Upload Example

In this article, we will see the laravel 8 image upload example. Image or file upload is the most common task...

Read More

Oct-06-2020