How to find a user in Laravel by Username?


There are various ways to find a Username in Laravel

Using the first() method

Example

The first() method returns the record found for the search value. It returns null if there are no matching records. To this method

You can make use of the method first() to find the user by username.

<?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"; } } }

Output

The output of the above code is −

The name exists in the table

Example 2

Using the SELECT Query

You can also make use of the SELECT query to find the username in the table. The example is as follows −

<?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"; } } }

Output

The output of the above code is

{"id":1,"name":"Siya Khan"}
The name exists in the table

Example 3

Using the DB facade

You can also make use of the DB facade to find the username as shown below −

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

Output

The output of the above code is −

 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
)

Updated on: 29-Aug-2022

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements