Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

mohansharma's avatar

Accessors not working in API

I have created an accessor to modify a database value

public function getImage1Attribute($value)
{
   return $value ? asset('storage/hosts/images/' . $value) : null;
}

but I am still getting original value in JSON API like this

{
    "message": "success",
    "data": {
        "id": 1,
        "image_1": "n0rVxA1L-1610381013.jpg",
        "created_at": "2021-01-07 18:02:56",
        "updated_at": "2021-01-11 16:03:33"
    }
}

I am passing response like this

return response([
      'message' => Lang::get('api.success'),
      'data' => HostDetail::find($id)
]);

I am not getting this problem with other models

I found out that the problem is with the column name image_1 but laravel is considering as image1. Is there any way around this?

0 likes
15 replies
bugsysha's avatar

Not sure what is your approach but I never use numbers when naming stuff.

Have you tried naming it getImage_1Attribute?

mohansharma's avatar

Me too. But this is an already existing application of one of the clients. Yes I tried getImage_1Attribute. But no luck

mohansharma's avatar

getImage1Attribute It does work when I access it like this $host->image_1, but not when sending the json response

bugsysha's avatar

How many models do have image_1 object property/database column?

bugsysha's avatar

That is then super easy change. Search and replace is your friend.

newbie360's avatar

will this work ?

protected $appends = ['image1'];
mohansharma's avatar

No, it doesn't. It has the same problem as image_1

newbie360's avatar

even ?

protected $appends = ['image_1'];
1 like
mohansharma's avatar

Yes appends only works for custom attributes. So this will give null

newbie360's avatar

search and replace in editor then xD in vscode it is very easy

mohansharma's avatar

Creating ApisResource is also an alternate solution, or instead of returning the model returning the columns one by one in an array is also a solution. I think I will have to go with these

newbie360's avatar

well, actually you are try to add extra code to fix another code, this may cause problems later

just like @bugsysha say, i also never name the accessor like that xD

Please or to participate in this conversation.