Laravel Eloquent firstWhere Explained with example

    By: Thad Mertz
    2 years ago

    In this post will see a example of laravel firstWhere. Explained in simply way about laravel eloquent firstwhere. I will use firstwhere in laravel.

    Here we see a very simple example of how to use firstWhere() with laravel eloquent. you can easily use firstWhere() with laravel 6, laravel 7 and laravel 8 version.

    If we need to get record from database using id then we can get from find() method, but when you need to get record from slug or title then you have to use first() method. But laravel eloquent provide firstWhere() method that will help you to easily get match first record.


    Here is a example:

    <?php
    
      
    
    namespace App\Http\Controllers;
    
    use App\Models\Post;
    
    class BlogController extends Controller
    
    {
    
        /**
    
         * Code Example
    
         *
    
         * @return response()
    
         */
    
        public function index()
    
        {
    
            /*
    
             	Ignore to write this query.
    
             	$post = Post::where("title", "world")->first(); 
    
            */
    
      
    
            $post = Post::firstWhere("title", "world");
    
      
    
            dd($post);
    
        }
    
    }