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
How To Install React JS Step By Step
How To Install React JS Step B...

In this article, we will see how to install React JS step by step. we will see how to set up an environment fo...

Read More

Aug-08-2022

How To Get Children Element In jQuery
How To Get Children Element In...

In this article, we will see how to get the children of this selector in jquery. You can use the find() method...

Read More

Jul-13-2022

Laravel 9 Yajra Datatable Example
Laravel 9 Yajra Datatable Exam...

In this artical we will see laravel 9 yajra datatable example. As we all used datatable on our backend side project, Her...

Read More

Mar-10-2022

How To Send E-mail Using Queue In Laravel 9
How To Send E-mail Using Queue...

In this tutorial, I will show you how to send e-mail using queue in laravel 9, Some time we can see many...

Read More

Feb-21-2022