Stop Repeating Expensive Logic in Laravel: Use once() the Right Way
In many Laravel applications, the same logic is often executed multiple times during a single request. This usually happens with database queries, configuration lookups, or helper functions that are reused across controllers, middleware, and views.
Laravel provides a clean and elegant solution for this problem: the once() helper.
❌ The Common Problem
Consider a helper function that fetches application settings:
function settings()
{
return Setting::first();
}
If this function is called in multiple places within the same request, the database query runs every time — leading to unnecessary performance overhead.
✅ The Correct Solution Using once()
function settings()
{
return once(function () {
return Setting::first();
});
}
🧪 Real-World Use Cases
User Role Lookup
function userRole()
{
return once(fn () => auth()->user()?->role);
}