我想用Laravel创建一个序列化器。目前,我有我的模型(CountryEntity
),它具有getSingleCountry()
的功能以隐藏特定字段(is_active
)。
模型
class CountryEntity extends Model
{
public $table = "countries";
protected $fillable = ['id', 'name', 'code', 'language', 'is_active'];
public $timestamps = false;
public function getSingleCountry()
{
$this->makeHidden['is_active'];
return $this;
}
}
Controller
public function show($id)
{
$country = $this->country_repository->getById($id);
$country = $country->getSingleCountry();
return Response::json(['type' => 'success', 'message' => 'Get country',
'data' => $country, 'status' => 200], 200);
}
但是字段“ is_active”始终可见...
这里的问题在方法调用中缺少()
。这行:
$this->makeHidden['is_active'];
没有明确地做任何事情。并没有引起Undefined index
错误,但这有点令人惊讶。
[当尝试调用类的方法时,您需要使用()
:
$this->makeHidden(['is_active']);
[
makeHidden()
方法接受一个参数数组,以暂时将其设置为模型上的protected $hidden
,在将模型转换为JSON
时会隐藏它们,并进行其他序列化。