Laravel find() and findOrFail() Eloquent Query Example

Laravel 6 , Laravel

Nicesnippets

185

16-01-2020


Hii Guys,

In this article, I will explain find and findOrFail method.you can require to find a record in the database table for using find and findOrFail method.you can find a method in add parameter to get a record.

I will show the difference between find and findOrFail method. find and findOrFail method input parameter one parameter.

if you can find a method to get a record but find a method to get only database table to record.you are required record not found and then show 404 Page. for a set if conditions. findOrFail method to get a record and not found record than show automatically 404 Page

Here the example of find() and findOrFail()

Example Find Method

Here is a simple example of find method, but if you use find() then you must check variable is null or not so you have to manually redirect to 404 page 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

If you will use findOrFail() then you don't require to check aboject null or not like find() method. it will automatic check and then run bellow code:

/**

* Show the application dashboard.

*

* @return \Illuminate\Contracts\Support\Renderable

*/

public function index(){

$userId = 10;

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

dd($user);

}

It will help you...


Recommended Posts