Laravel Eloquent firstWhere() Example

Avatar
C

Callum Davies

Senior Backend Engineer••
7942Views
5mRead
0Reactions

This post will give you an example of Laravel's firstWhere eloquent. You will learn how to use firstWhere eloquent and where to use it.

Sometimes, we need to fetch a single record from a database or collection using ID, then we simply use the find() method. But when you need to get a record from slug or name, then you have to use the first() method. But Laravel eloquent provides the firstWhere() method that will help you easily get a match record from the database.

Let's see an example:

<?php
  
namespace App\Http\Controllers;
  
use App\Models\Category;
  
class CategoryController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index()
    {
  
        $category = Category::firstWhere("name", "Laravel");
  
        dd($category);
    }
}

Example 2:

 

$collection = collect([
    ['name' => 'PHP', 'slug' => 'php'],
    ['name' => 'Laravel', 'slug' => 'laravel'],
    ['name' => 'Javascript', 'slug' => 'js'],
    ['name' => 'Node.js', 'slug' => 'node-js'],
]);
 
$collection->firstWhere('name', 'PHP');

 

Output:

['name' => 'PHP', 'slug' => 'php']

Connect with KoderSolution 🚀

Master modern software engineering, scalable architectures, and advanced backend systems.

What's your setup?How does your production stack handle background jobs? Are you using Redis with Horizon, or cloud queues like AWS SQS?
Callum Davies
C
Written by•Senior Backend Engineer

Callum Davies

PHP & Laravel practitioner since v5.4. Big believer in thin controllers, explicit return types, and boring modular architecture that doesn't page you on weekends.

React to this article

Recommended Articles

View all articles