When you want to format certain Eloquent models before setting/retrieving in Laravel, you would certainly reach for the accessors and mutators. So, let’s say we have a field called tax in the orders table and if we want to set the computed tax on the field, we would need to define a mutator with the set{Foo}Attribute name format in the model like so. namespace App\Models; use Illuminate\Database\Eloquent\Model; class Order extends Model { /** * The table associated with the model. * * @var string */ protected $table = 'orders'; public function setTaxAttribute($value) { return ($value * 20)/100; }}
protected function tax(): Attribute { return new Attribute( function($value) { return ($value * 20)/100; // raw tax }, function($value) { return ($value * 100)/20, // computed tax }); }