loading...

findorfail laravel

pakainfocom profile image pakainfo ・2 min read

In this Post, We will describe Laravel find and findOrFail method.you can need to eloquent find a record in the database table for using find as well as findOrFail funcion.you can eloquent find a funcion in add argument to get a row.

Laravel 7/6/5 find() and findOrFail() Eloquent Query

We will display the difference between eloquent find and findOrFail method. eloquent find as well as findOrFail funcion input argument single argument.

if you can find a method to get a row but eloquent find a funcion to get only database table to row.you are need row not found as well as then display 404 Page. for a appaly if conditions. findOrFail funcion to get a record as well as not found row than display automatically 404 Page

How to use findOrFail() method?

Sometimes you may wish to throw Not Found Exceptions if a particular row is not found. To do this, you may use the findOrFail method in Laravel findOrFail funcion with generates as well as Not Found Exceptions if particular record is not found.

$model = Customer::findOrFail(1);

What is the difference between these methods?

  • find()
  • findOrFail()
  • first()
  • firstOrFail()
  • get()
  • list()
  • toArray()
  • all()
  • destroy()
  • delete()
  • save()

You can visit my Article with More Examples : click here

Here the example of find() and findOrFail()

Example Find Method

Here is a simple example of eloquent find method, but if you use find() then you must check each variable is null or not(Not Found Exceptions) so you have to manually sent or redirect to 404 page like as following:

/**
 * Show the application dashboard.
 *
 * @return \Illuminate\Contracts\Support\Renderable
 */
public function index(){
    
  $customerId = 78;
  $customer  = Customer::find($customerId);

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

  dd($customer);
}

Example findOrFail Method

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

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

  $customer  = Customer::findOrFail($customerId);
  
  dd($customer);
}

You can visit my Article with More Examples : click here

Posted on by:

pakainfocom profile

pakainfo

@pakainfocom

My name is Angular King. I'm a full-stack developer, entrepreneur and owner of Pakainfo. I live in India and I love to write

Discussion

pic
Editor guide