php 通过用户名在 Laravel 中查找用户
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32147247/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Find User in Laravel by Username
提问by Brandon
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?
所以通常如果你在 laravel 中可以访问用户的 id,你可以运行 User::find($id),但是说你无权访问用户的 id,只有他们的用户名。有没有比使用 DB::query 定位用户更好的方法?
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;
回答by mdamia
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();
回答by Hamidreza Bayat
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_id = User::select('id')->where('username', $username)->first();
回答by Angel M.
$user_id = DB::table('users')->where('username', $user_input)->first();
without "->id"
没有“-> id”
check here: http://laravel.com/docs/5.0/queries

