FatalThrowableError对laravel 5.5 API请求调用成员函数where()on null

时间:2018-02-02 07:06:19

标签: php mysql json laravel-5.5

您好我正在尝试从laravel构建API。我正在使用雄辩的资源来管理API。我在传递数据库中不存在的id时得到FatalThrowableError Call to a member function where() on null

路线:

 Route::resource('hotel', 'HotelController',['only'=>['index','show']]);

资源:

public function toArray($request)
{
    return [
        'id' => $this->hotel_id,
        'name' => $this->name,
        'summary' => $this->summary,
        'description' => $this->description,
        'contactno' => $this->contactno,
        'address' => $this->address,
        'latitude' => $this->latitude,
        'longitude' => $this->longitude,
        'star' => $this->star,
        'image' => base_resource_url().$this->image,
        'facilities' => $this->facility,
      ];
  }
}

控制器:

public function show($id) 
{
    return new HotelResource(Hotel::find($id)->where(['suspend'=>1,'verify'=>1])->first());
}

当我传递数据库中存在的ID时,我可以获取json数据但是当我在控制器的show($ id)方法中传递数据库中不存在的ID时,我得到FatalThrowableError Call to a member function where() on null怎么能我在laravel中处理这个异常,抛出一些可读的json错误响应,如:

{error : not data found with accosiated ID}

1 个答案:

答案 0 :(得分:1)

您需要先检查记录是否存在。例如:

public function show($id) 
{
    if ($hotel = Hotel::find($id)) {
         // hotel exists
    }

    abort(404, 'Hotel does not exist');
}

<强>更新

Hotel::find($id)只会返回1或0条记录。应用first()后面的where子句是没有意义的。

// is this what you mean?
Hotel::where(['id' => $id, 'suspend' => 1, 'verify' => 1])->first()

更新2

public function show($id) 
{
    if ($hotel = Hotel::where(['id' => $id, 'suspend' => 1, 'verify' => 1])->first()) {
        return new HotelResource($hotel);
    }

    abort(404, 'Hotel does not exist');;
}