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?

这是我目前的解决方案,我想知道是否有人知道更好的方法.

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

推荐答案

是的,使用这个模型更好.就这样

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

Laravel相关问答推荐

LaravelEloquent 的模型如何将值从控制器内部的函数传递到Render()

Uncaught ReferenceError:未定义require[Shopify PHP React Browser问题]

Laravel Eloquent:组合列(或自定义属性)上的 Where 子句

如何在 vue 模板中引用 laravel csrf 字段

Laravel 5.4 中的自定义助手类

我的composer 不会完全用 Laravel 4 更新它会被artisan卡住

如何在 Laravel 5.5 的 FormRequest 类中返回自定义响应?

Laravel Blade 没有额外的空格?

laravel 预期响应代码 250 但得到代码530

Laravel 5.3 Electron邮件队列中不允许序列化关闭

在 Laravel 4 迁移中创建 MYSQL 过程

如何在 laravel 中解码 Json 对象并在 laravel 中应用 foreach 循环

反向代理后面的 Laravel 路由

Class类 App\Http\Controllers\Auth\Request 不存在.

使用 Laravel 使用 2 个磁盘复制文件

Composer RuntimeException - 无法加载软件包 mews/purifier

使用哪个 Auth::check() 或 Auth::user() - Laravel 5.1?

Laravel 部署……有标准的方式吗?

如果在 Laravel 5.1 中找不到路由,则显示 404 页面

Distinct values with pluck