For getting every new tutorial link Please join our telegram group

Part 10 laravel eloquent model findOrFail vs firstOrFail method

This laravel eloquent tutorial about the findOrFail vs firstOrFail method with example. These two methods same as the first or find method but here if data is not available then a not found page return.

Laravel findOrFail vs firstOrFail method

Laravel findOrFail and firstOrFail both methods return a single row data which is match first according to condition. findOrFail() method work as eloquent find() method and firstOrFail() work as eloquent first() method. In these methods, if not a single row matches our condition then return a 404 not found page.

findOrFail() method take a primary column like an id it not contain extra where condition it find this id row in table or firstOrFail method use or not some where condition for getting data.

Example 1 for 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);
  }

}
Example 2 for firstOrFail() 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::where('age','<', '15')->firstOrFail());

    dd($student);
  }

}

You read this tutorial on advanced web tutorial. here we provide laravel beginners to advanced 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