DEV Community

Md. Asif Rahman
Md. Asif Rahman

Posted on

3 2

Single method accessors and mutators in laravel

We have already known the usage of accessors and mutators. We use accessors in laravel model to modify any field data while retrieving the records and mutators to modify any field data while inserting to database.

So, to modify any field before, we needed two separate methods for a single filed i.e. one method for accessor and one for mutator but in latest laravel release I mean in laravel 8.77.0, we can use a single method for both accessor and mutator using closure .

Given below is the syntax for single mehtod accessor and mutator:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Carbon\Carbon;
class Order extends Model
{

    /**
     * Get the order tax.
     */
    protected function order_date(): Attribute
    {
        return new Attribute(
            fn ($value) => Carbon::parse($value)->format('d-m-Y'), // accessor
            fn ($value) => Carbon::parse($value)->format('Y-m-d'), // mutator
        );
    }
}
Enter fullscreen mode Exit fullscreen mode

In the above closures, the first closure is for accessor and the next for mutator.

Sentry blog image

How to reduce TTFB

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

In this article, we’ll see how we can identify what makes our TTFB high so we can fix it.

Read more

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more