Laravel Eloquent firstWhere() Example

This post will give you an example of laravel 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 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:

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");

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');



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

Related Post



I am a thinker, not a talker.