如何透過使用者名稱在 Laravel 中查詢一個使用者?


在 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 外觀

還可以使用 DB 外觀查詢使用者名稱,如下所示 -

<?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
)

更新於: 2022-08-29

3 千+ 次檢視

開啟你的 事業

完成課程以獲得認證

開始
廣告