如何在 Laravel 中通过用户名查找用户?
laravelphpserver side programming更新于 2025/4/30 2:37:17
在 Laravel 中有多种方法可以查找用户名
使用 first() 方法
示例
first() 方法返回根据搜索值找到的记录。如果没有匹配的记录,则返回 null。此方法
您可以使用方法 first() 通过用户名查找用户。
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\Student; class StudentController extends Controller { public function index() { $userName = 'Siya Khan'; // Record being searched $recordCount = Student::where('name', '=',$searchName)->first(); if ($recordCount) { echo "The name exists in the table"; } else { echo "No data found"; } } }
输出
上述代码的输出是 −
The name exists in the table
示例 2
使用 SELECT 查询
您还可以使用 SELECT 查询在表中查找用户名。示例如下 −
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\Student; class StudentController extends Controller { public function index() { $userName = 'Siya Khan'; // Record being searched echo $userdetails = Student::select('id','name')->where('name', $userName)->first(); echo "<br/>"; if ($userdetails) { echo "The name exists in the table"; } else { echo "No data found"; } } }
输出
上述代码的输出是
{"id":1,"name":"Siya Khan"}
The name exists in the table
示例 3
使用 DB Facade
您还可以使用 DB Facade 查找用户名,如下所示 -
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; //use App\Models\Student; use DB; class StudentController extends Controller { public function index() { $userName = 'Siya Khan'; // Record being searched $studentdetails = DB::table('students')->where('name', $userName)->first(); print_r($studentdetails); } }
输出
上述代码的输出是 −
stdClass Object( [id] => 1 [name] => Siya Khan [email] => siya@gmail.com [created_at] => 2022-05-01 13:45:55 [updated_at] => 2022-05-01 13:45:55 [address] => Xyz )

