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
Laravel 10 Apexcharts Bar Chart Example
Laravel 10 Apexcharts Bar Char...

In this article, we will see the laravel 10 apexcharts bar chart example. Here, we will learn about how to create a bar...

Read More

May-24-2023

Top 20 Best Javascript Tips and Tricks
Top 20 Best Javascript Tips an...

Welcome to the fascinating world of JavaScript, where innovation and creativity converge to deliver dynamic and interact...

Read More

Aug-14-2023

How To Add Foreign Key In Laravel 10 Migration
How To Add Foreign Key In Lara...

In this article, we will see how to add a foreign key in laravel 10 migration. Here, we will learn about laravel 10...

Read More

May-05-2023

Laravel 11 Spatie Media Library Example
Laravel 11 Spatie Media Librar...

Hello, laravel web developers! In this article, we'll see how to install spatie media library in laravel 11. Here, w...

Read More

Jul-05-2024