Laravel Accessors, Mutators, and Query Scopes Explained

Learn how to use Laravel accessors, mutators, and query scopes to format data automatically and reuse common query logic.

As your models grow, you'll want to format data consistently and avoid repeating the same query conditions everywhere. Accessors, mutators, and query scopes solve exactly this — keeping formatting and query logic inside the model, where it belongs. Accessors: Formatting Data When You Read It An accessor transforms an attribute's value automatically whenever you access it. namespace App\Models; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Casts\Attribute; class Product extends Model { protected function price(): Attribute { return Attribute::make( get: fn ($value) => '$' . number_format($value, 2), ); } } Now, anywhere you access $product->price , it's automatically formatted: echo $product->price; // "$25.99" instead of "25.99" Mutators: Formatting Data Before It's Saved A mutator transforms a value automatically before it's stored in the database....

Home · Projects · Articles · Developer tools · Contact