Laravel's accessor, how to give a parameter when using toJson.
class App extends Model
{
...
public function getUrlAttribute($os)
{
switch ($os) {
case 'android':
return $this->attributes['url_android'];
case 'ios':
return $this->attributes['url_ios'];
default:
return '';
}
}
}
$app = new App;
$app->toJson();
I hope that when calling the toJson function, I can determine the specific type of $os, and then return the desired field as the value of the url.
I’ve been searching for a long time but I still can’t find the usage. Please tell me.
黄舟2017-06-05 11:11:29
public function toJson($options = 0)
{
return json_encode($this->jsonSerialize(), $options);
}
public function jsonSerialize()
{
return $this->toArray();
}
You can inherit the toJson method to modify it
public function toJson($options = 0)//自己添加参数
{
//这里修改this里的变量
return json_encode($this->jsonSerialize(), $options);
}