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

princeoo7's avatar

Modify column on the fly in api output in laravel

I have a media table in relation to the user. when I save a media for the user, normally only URL like storage/folder/filename is store in the DB. How to add the base url to this on the fly when the API is been called?

In short, what I need to do is a prefix that column with the domain name in API only.

0 likes
10 replies
princeoo7's avatar

@sti3bas that gives me the URL which I have already mentioned.

result is storage/folder/filename and not domain/storage/folder/filename, which is what I want. Also I need it to be only provided in the API result and don't want to save the data in that way in database.

princeoo7's avatar

@sti3bas this does gives me full URL but one problem in this. for some reason, the URL is like domain/media-folder/media-file and is not accessible. but if I add storage beforemedia-folder like domain/storage/media-folder/media-file I am able to access the file.

princeoo7's avatar

that is what I came up with this, before after your answer. Now only one issue left ! how to override the data of the URL column with this URL output in the model itself.

currently Implemented the $append method but it gives an extra row in API. What shall I do for this ?

Sti3bas's avatar
Sti3bas
Best Answer
Level 53

how to override the data of the URL column with this URL output in the model itself.

Add an accessor in your model class:

public function getUrlAttribute($value)
{
   return asset(Storage::url($value));
}

https://laravel.com/docs/6.x/eloquent-mutators#defining-an-accessor

currently Implemented the $append method but it gives an extra row in API. What shall I do for this ?

Make sure you use the field name in the method get{field}Attribute, then you will not need to append new attribute.

2 likes
princeoo7's avatar

@sti3bas the above answer worked for me perfectly. Thank you for your assistance :D

One last request / help I need now.

as I told that the media file is in relation to user. now not every user have media file uploaded. so how to only get the records of user where they have media file record with them.

what I am doing is

User::with(['media'])->whereStatusId(2)->orderBy('order_id', 'ASC')->get(),

what should I do here to only get the Users, who have media records.

Please or to participate in this conversation.