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

Fathom Analytics | Fast, simple and privacy-focused website analytics. Fathom Analytics | Fast, simple and privacy-focused website analytics.
Achieve superior email deliverability with ToastMail! Our AI-driven tool warms up inboxes, monitors reputation, and ensures emails reach their intended destination. Sign up today for a spam-free future. Achieve superior email deliverability with ToastMail! Our AI-driven tool warms up inboxes, monitors reputation, and ensures emails reach their intended destination. Sign up today for a spam-free future.
Community Partners