Laravel Eloquent firstWhere() Example

Avatar
M

Maksudur Rahman

Software Engineer

7609Views
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']

Recommended Resources & Courses

React to this article