user8506374
user8506374

Reputation:

get attribute accessor only for specific method in laravel

I want to modify some values of my query result for API call. here's my query

public function modules()
{
    Module::select('id','name','image')->get()->toJson();
}

so I want to modify image value, add full path to it. I added accessor

public function getImageAttribute($image)
{
    return asset($image);
}

and it works fine, but the problem is now it will be affecting this column every time i try to retrieve it. is there way to use this accessor(getImageAttribute) only for modules method?

Upvotes: 1

Views: 1599

Answers (1)

Hamoud
Hamoud

Reputation: 1929

You could get rid of the accessor and update the image path inside the modules method.

public function modules()
{
    return Module::select('id', 'name', 'image')->get()->map(function ($module) {
        $module->image = asset($module->image);
        return $module;
    })->toJson();
}

Upvotes: 3

Related Questions