无法使用findOrFail()检索模型。 IDE没有看到此方法。怎么了?

时间:2017-05-07 07:10:25

标签: laravel laravel-5.4 laravel-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);

}

订单模型已连接到控制器文件:

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

IDE说它不知道firstOrFail()函数。当我尝试使用Postmen通过XMLHttpRequest获取数据时,Controller方法不起作用。当我从方法中删除这部分代码时:

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

控制器方法开始工作。我认为问题出在firstOrFail()方法中,但我不明白为什么。

1 个答案:

答案 0 :(得分:1)

如果您按主要ID找到而不是使用findOrFail

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

如果您发现其他列而不是使用firstOrFail

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