Date:

Share:

Improved single-method accessors and mutators in Laravel 8.x – Amit Merchant – A blog on PHP, JavaScript, and more

Related Articles

When you want to design certain Eloquent models before setting up / retrieving in Laravel, you are probably pulling the aids and motors.

I have already talked about this in detail in one of the posts. But if I have to give a summary of it, I will explain it with an example.

Old accessories and motors

So suppose we have a field called tax In the orders Table And if we want to define the tax calculated on the field, we will need to define a Motor with the setFooAttribute Format name in model so.

namespace AppModels;

use IlluminateDatabaseEloquentModel;

class Order extends Model

    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'orders';

    public function setTaxAttribute($value)
    
        return ($value * 20)/100;
    

So, from now on, e tax The field will be saved with the calculated value.

$order = AppOrder::find(5);

$order->tax = 15; // tax in percentage
// will be saved as "3"

So too when you want to retrieve the raw tax Order value, you will need to set a accessory with the getFooAttribute Format name in model so.

namespace AppModels;

use IlluminateDatabaseEloquentModel;

class Order extends Model

    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'orders';

    public function getTaxAttribute($value)
    
        return ($value * 100)/20;
    

In this way, when e tax Returned to order, this will be the gross tax (without any calculation).

$order = AppInventory::find(5);

$orderTax = $order->tax; 
// retrieved back as 15

The problem

This is the standard way to set up accessories and motors in Laravel. But the problem with this approach is that it is not very elegant because it needs two different methods for retrieving and defining model fields.

also, as per Taylor, it’s not “style” Laravel as a follow-up frame throughout.

So, he invented a solution that would reduce this operation to one method that would make this feature smoother.

Improved accessories and motor

God Last release Laravel’s now comes with an alternative way to set up accessories / motors, all in one method.

According to PR, the framework now comes with IlluminateDatabaseEloquentCastsAttribute A repeat type that allows you to define an attribute behavior / mutation behavior in a single method.

So, if we want to rewrite the previous example with this approach, here’s how we can do it.


namespace AppModels;

use IlluminateDatabaseEloquentModel;
use IlluminateDatabaseEloquentCastsAttribute;

class Order extends Model

    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'orders';

    /**
     * Get the order tax.
     */
    protected function tax(): Attribute
    
        return new Attribute(
            fn ($value) => ($value * 20)/100, // accessor
            fn ($value) => ($value * 100)/20, // mutator
        );
    

As you can see, you can directly define a method with the same name as the field. In our case, it’s the tax method.

From this method, you can then return the Attribute Type. where is the Attribute The constructor gets two Can be called As arguments.

  • God First argument Is a callable where you can set logic for accessory.
  • God Second argument It can be called where you can define the logic Mutation / permanent Field value.

The example uses shorter Arrow method Syntax But if you have a business logic that can not be done in one line, you can write it using the usual closures that way.

protected function tax(): Attribute

    return new Attribute(
        function($value) 
            return ($value * 20)/100; // raw tax
        ,
        function($value) 
            return ($value * 100)/20, // computed tax
         
    );

It’s even better with PHP 8

Now, if you’re on PHP 8+, This syntax is even sweeter and more readable when you use it with the specified parameters.

protected function tax(): Attribute

    return new Attribute(
        get: fn ($value) => ($value * 20)/100, // raw tax
        set: fn ($value) => ($value * 100)/20, // computed tax
    );

Source

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Popular Articles