Category: Laravel, Laravel, PHP, PHP, javascript, javascript

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 }); }
Newsletter

Get the latest Laravel/PHP jobs, events and curated articles straight to your inbox, once a week

Glimpse streamlines Laravel development by seamlessly deploying GitHub pull requests to preview environments with the help of Laravel Forge. Glimpse streamlines Laravel development by seamlessly deploying GitHub pull requests to preview environments with the help of Laravel Forge.
Fathom Analytics | Fast, simple and privacy-focused website analytics. Fathom Analytics | Fast, simple and privacy-focused website analytics.
Shirts painstakingly handcrafted by under-caffeinated developers. Shirts painstakingly handcrafted by under-caffeinated developers.
Community Partners