我写了一个变换器类,用于在API中输出数据:
APPTRANSFORMER:
<?php
namespace App\Transformer;
use App\Classes\AED;
use League\Fractal\TransformerAbstract;
class AEDTransformer extends TransformerAbstract {
public function transform(AED $aed) {
return [
'owner' => $aed->owner,
'street' => $aed->street,
'latitude' => $aed->latitude,
'longitude' => $aed->longitude,
'annotationType' => $aed->annotation_type
];
}
}
获取所请求数据的控制器方法:
控制器:
// Show specific AED
public function show($id) {
// Find AED by ID
$aed = AED::find($id);
$rawData = $this->respondWithItem($aed, new AEDTransformer);
$meta = ['meta' => 'TestMeta'];
$data = array_merge($rawData, $meta);
if (!$aed) {
return $this->respondNotFound("AED existiert nicht.");
}
return $data;
}
当我调用URL时,我收到错误:
AEDTransformer.php第16行中的ErrorException:参数1传递给 App \ Transformer \ AEDTransformer :: transform()必须是。的实例 App \ Classes \ AED,null给定,调用 /home/vagrant/Projects/MFServer/vendor/league/fractal/src/Scope.php on 第307行和定义
AED CLASS:
<?php
namespace App\Classes;
use Illuminate\Database\Eloquent\Model;
class AED extends Model {
protected $table = 'aeds';
protected $fillable = ['owner', 'street', 'postal_code', 'locality', 'latitude', 'longitude', 'annotation_type'];
public $timestamps = true;
public $id;
public $owner;
public $object;
public $street;
public $postalCode;
public $locality;
public $latitude;
public $longitude;
public $annotation_type;
public $distance;
public function set($data) {
foreach ($data as $key => $value) {
$this->{$key} = $value;
}
}
}
我认为它必须与&#34;扩展模型&#34;在AED班,但我没有看到原因。这只是一个扩展。或者我是否错误地查看错误的地方并理解错误信息?
答案 0 :(得分:0)
您收到此错误是因为$aed = AED::find($id);
正在返回null
,这意味着该记录不存在。
你可以这样做
public function show($id) {
// Find AED by ID
$aed = AED::find($id);
if (!$aed) { //just to be sure
return $this->respondNotFound("AED existiert nicht.");
}
$rawData = $this->respondWithItem($aed, new AEDTransformer);
$meta = ['meta' => 'TestMeta'];
$data = array_merge($rawData, $meta);
return $data;
}