Laravel 7/6 find() and findOrFail() Eloquent Query Example
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...
- How to Notifications With database Driver in Laravel 11?
- How to Send Email Via Notification in Laravel 11?
- How to Install and Configure Laravel 11 Debugbar?
- How to Like Dislike System in Laravel 11?
- How to Paginate a Model with Relationship in Laravel 11?
- Laravel 11 Upload Files to Amazon S3 Example
- Laravel 11 Send WhatsApp Messages Example
- Laravel 11 Rest API Authentication Using JWT Tutorial