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

zoldic's avatar

Get UserId with UserName without query

Hi guys; Do you guys know how to Get UserId with UserName without query?

The regular way with query in the controller file

public function testing($name)
{
    $userId = User::where('name', $name)->first()->id;
}

is there any better way to get the id without the query? Thanks

0 likes
8 replies
tykus's avatar
tykus
Best Answer
Level 104

No*.

* unless you choose to cache all username/password as key/value pairs

1 like
jdunsmore's avatar

Is the user the logged in user?

If so then do:

auth()->user()->userName;
rumm.an's avatar

if you only need id that can be achieved with Auth::id().

tykus's avatar

Who says that the user in this case is the authenticated user?

zoldic's avatar

No, it is not the logged in user

So it is not possible

tykus's avatar

Not without storing that relationship elsewhere.

What problem are you trying to solve?

1 like
zoldic's avatar

I just want to reduce the usage of query if possible

in this case

$userId = User::where('name', $name)->first()->id;

What do you mean by "storing that relationship elsewhere"?

can you give an example of that, using the id and name from the user_table

Please or to participate in this conversation.