0

I have method in controller:

public function read(ReadRequest $request){

    $r  = $request;
    $id = $r->id;
    $order = null;

    try{
        $order= Order::firstOrFail($id);
    }catch(ModelNotFoundException $e){
        return response()->json(["message"=>"Order Id doesn't exist."], 404);
    }


    return response()->json(["order"=>$order], 200);

}

Order model is connected to controller file:

namespace App\Http\Controllers;
use App\Order;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Http\Request;
use Illuminate\Http\Response;

IDE says that it doesn't know firstOrFail() function. Controller method doesn't work when I'm trying to get data through XMLHttpRequest using Postmen. When I delete this part of code from method:

    try{
        $order= Order::firstOrFail($id);
    }catch(ModelNotFoundException $e){
        return response()->json(["message"=>"Order Id doesn't exist."], 404);
    }

Controller method starts to work. I think the problem is in firstOrFail() method, but I don't understand why.

Evgeniy Miroshnichenko
  • 1,788
  • 2
  • 19
  • 30

1 Answers1

1

if you find by primary ID than use findOrFail

$order= Order::findOrFail($id);

If you find by another column than use firstOrFail

$order = Order::where('column', '=', $id)->firstOrFail();

Md. Sahadat Hossain
  • 3,210
  • 4
  • 32
  • 55
  • Thank. I wonted to use findOrFail(). During other debugs I changed the name of the method to firstOrFail() and forget to replace it back. So, I have to rest) – Evgeniy Miroshnichenko May 07 '17 at 07:31