find() and findOrFail() Eloquent Query in Laravel Example

Share Me
  •  
  •  
  •  
  • 1
  •  
  •  
  •  
  •  
  •  
  •  
  •  
    1
    Share

Today now in this article, I will explain with you a example of find and findOrFail method. Here you can require to find a record in the database table for by using find and findOrFail method. So from here you can find a method in add parameter to get a records.

So here i will show the difference between find and findOrFail method. Now we see find and findOrFail method input parameter one parameter.

So if we can find a method to get a record but find a method to get only from the database table to record. So you are required record not found and then show 404 error Page. For a set if conditions findOrFail method to get a record and if not found any record than it show automatically 404 Page

Now here the example of find() and findOrFail() method

Example Find Method

For here is a very simple example of find method, but if we use find() method then we must need to check variable is null or not . So we have to manually redirect to 404 page as like as bellow:

/**
 * Show the application dashboard.
 *
 * @return \Illuminate\Contracts\Support\Renderable
 */
public function index(){
    
  $userId = 10;
  $user  = User::find($userId);

  if(is_null($user)){
  	return abort(404);
  }

  dd($user);
}
Example findOrFail Method

Now If we will use findOrFail() then we don’t require to check the object is null or not like find() method. So it will automatic check and then it run bellow code:

/**
 * Show the application dashboard.
 *
 * @return \Illuminate\Contracts\Support\Renderable
 */
public function index(){
    
  $userId = 10;

  $user  = User::findOrFail($userId);
  
  dd($user);
}

Read Also : Laravel 8 Eloquent Global Scope Tutorial Example

I hope it will help you. Also you can follow us on Facebook

About Shahriar Sagor

My name is Shahriar sagor. I'm a developer. I live in Bangladesh and I love to write tutorials and tips that will help to other Developer's. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.

View all posts by Shahriar Sagor →