Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find User in Laravel by Username

So typically if you have access to the id of a user in laravel you can run User::find($id), however say you don't have access to the user's id and only their username. Is there a better way than using DB::query to locate the user?

This is my current solution and was wondering if someone possibly knew a better way.

$user_id = DB::table('users')->where('username', $user_input)->first()->id;
like image 349
Brandon Avatar asked Aug 21 '15 18:08

Brandon


People also ask

How to display user name after login in Laravel?

You can use the Auth facade. Auth::user()->username // or whatever the column name is. If you want to fetch the user's fullname in a proper way instead of doing Auth::user()->firstname.

How can we get data from database in controller in laravel?

After configuring the database, we can retrieve the records using the DB facade with select method. The syntax of select method is as shown in the following table. Run a select statement against the database.


2 Answers

Yes, even better using the model. just like this

User::where('username','John') -> first();
// or use like 
User::where('username','like','%John%') -> first();
User::where('username','like','%John') -> first();
User::where('username','like','Jo%') -> first();
like image 107
mdamia Avatar answered Sep 30 '22 06:09

mdamia


It depends. If a user is logged in you can have any information you want by:

$field = Auth::user()->field;

But if they are not logged in and you just want their user_id you can use:

$user_id = User::select('id')->where('username', $username)->first();
like image 26
Hamidreza Bayat Avatar answered Sep 30 '22 06:09

Hamidreza Bayat