Laravel Eloquent firstWhere() Example
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.
Read more architectural deep-dives, systems tutorials, and engineering guides on kodersolution.com.
Subscribe to @kodersolution for concise, animated system design breakdowns and technical shorts.
Follow our official page for daily development tips, architecture discussions, and community updates.
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.