Evgeniy Miroshnichenko
Evgeniy Miroshnichenko

Reputation: 1865

Can't retrieve model with findOrFail(). IDE doesn't see this method. What is wrong?

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.

Upvotes: 0

Views: 780

Answers (1)

Md. Sahadat Hossain
Md. Sahadat Hossain

Reputation: 3236

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();

Upvotes: 1

Related Questions