logo
podcast Podcast
get help Get Unstuck

Improve user experience while keeping an eye on performance

Auto-select a single client without unnecessary queries

Joel Clermont
Joel Clermont
2025-05-23

I like to add small touches to a user interface to make the application just a bit nicer to use day to day.

For example, I was working on a project where you could use a "client picker" at the top of the application to shift context from one client to another.

On some screens, picking a client is a necessity in order to see the data, but most users only ever have access to one client. So I built a simple piece of logic to automatically pick that one-and-only client for those users, without requiring them to do it.

Here's what the first version of this code looked like:

$authorizedClients = Client::forUser($request->user())->get();

if ($authorizedClients->count() === 1) {
 $request->setCurrentClient($authorizedClients->first()->id);
}

This worked as expected, but it's doing more work than necessary.

I don't really care if a user has 2 clients or 2,000 clients. As soon as they have more than 1 client, I will build the full list and make them pick one.

So why load ALL the clients to make that decision? It was a waste of resources, especially for administrative users that might have access to hundreds of clients.

This refined version of the code gives me the same desired result, with a less expensive query:

$authorizedClients = Client::forUser($request->user())->take(2)->get();

if ($authorizedClients->count() === 1) {
 $request->setCurrentClient($authorizedClients->first()->id);
}

That one small change adding on take(2) sped up the query a fair bit for those admin users.

Here to help,

Joel

P.S. Is there a part of your application that is slower than you would like? We can help with that.

Toss a coin in the jar if you found this helpful.
Want a tip like this in your inbox every weekday? Sign up below 👇🏼
email
No spam. Only real-world advice you can use.