Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Ligonsker's avatar

first()/firstOrFail() with non-unique names - am I safe that I'll get the correct row?

When a user creates an account, a default folder named "main" is created for him. But the name is not unique and he can create more folders named "main".

And in one of my Controllers, I use the firstOrFail() method that's supposed to get the default "main" folder:

$folder = Auth::user()->folders()->where('name', '=', 'main')->firstOrFail();

Am I safe that it will always get the initially created "main" folder (Which will have the lowest id in the DB table for that user)? Or I should use a different query to make sure?

0 likes
2 replies
OussamaMater's avatar

Well, to be honest, I would simply add a flag column to the table called "main", set to true only for the default "main", this way you are more safe, and have a flexible table if you decide to switch things up.

$folder = Auth::user()->folders()->whereDefault(true)->firstOrFail();

And you can use query scope so it's clean and more flexible in your code when you decide to change the logic

$folder = Auth::user()->mainFolder()->firstOrFail();

Docs:

1 like
krs's avatar

I would order the result, either by id or by the created_at column:

$folder = Auth::user()->folders()->where('name', '=', 'main')->orderBy('id')->firstOrFail();

or

$folder = Auth::user()->folders()->where('name', '=', 'main')->oldest()->firstOrFail();

The first one only will work, if your key uses autoincrement (not with uuid's e.g), but will be faster because the dbms can use the index of your key.

Please or to participate in this conversation.