php - How to use Lavavel's accessor
某草草
某草草 2017-06-05 11:09:29
0
1
744

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.

某草草
某草草

reply all(1)
黄舟
    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);
    }
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template