Find User in Laravel by Username

大憨熊 提交于 2019-12-19 16:41:35

问题


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;

回答1:


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();



回答2:


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();



回答3:


$user_id = DB::table('users')->where('username', $user_input)->first();

without "->id"

check here: http://laravel.com/docs/5.0/queries



来源:https://stackoverflow.com/questions/32147247/find-user-in-laravel-by-username

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!