For getting every new tutorial link Please join our telegram group

Part 4 laravel eloquent first vs find and findOrFail vs firstOrFail method tutorial

This laravel eloquent model tutorial about how to get single row data by fisrt, find and findOrFail method with example.

Laravel first vs find vs findOrFail vs firstOrFail method

  1. first()
  2. find()
  3. findOrFail()
  4. firstOrFail()

Laravel first() method

laravel provides first() method for getting a single row record. first() method use after a where condition and getting record that are match first. Example of first() method

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Student;

class StudentController extends Controller{
 public function index(){
    $student = Student::where('age' > '21')->first();

    dd($student);
  }

}

Laravel find() method

laravel find() method also retrieve a single row record but it get record which primary key given in find($id) method. it not use where condition. Example of find() method

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Student;

class StudentController extends Controller{
 public function index(){
    $id = 7;
    $student = Student::find($id);

    dd($student);
  }

}

Laravel findOrFail() method

laravel findOrFail retrieve single row same as find() method it takes a primary key value in findOrFail($id) method and if any record exist on this id return data else return not found page. Example of findOrFail method.

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Student;

class StudentController extends Controller{
 public function index(){
    $id = 7;
    $student = Student::findOrFail($id);

    dd($student);
  }

}

Laravel firstOrFail() method

laravel firstOrFail method retrieve single row same as the first method it uses where condition and give first match data but if according to where condition no data match than it gives not found page. For example firstOrFail method if no one student find less than age 15 then it gives not found page.

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Student;

class StudentController extends Controller{
 public function index(){
    $id = 7;
    $student = Student::where('age','<', '15')->firstOrFail());

    dd($student);
  }

}

You read this tutorial on advanced web tutorial. here we provide beginners to advanced laravel tutorial.

php laravel developer anmol sharma

Anmol Sharma

I am a software engineer and have experience in web development technologies like php, Laravel, Codeigniter, javascript, jquery, bootstrap and I like to share my deep knowledge by these blogs.

Related tutorial links