0

I'm fearly new to laravel, please assist me with resolving this issue. I need to edit my response on the image attribute to return as a URL instead of just the image name stored on the database on the array response.

Here is my source code:

/**
 * Display a listing of the resource.
 *
 * @return \Illuminate\Http\Response
 */
 public function serv_list(){
   $services = Add_Service::all();

   return $services;
 }

current response:

[
    {
        "id": 1,
        "service_name": "Hair",
        "desc": "Everything that has to do with hair and more",
        "image": "1590713947.jpg",
        "created_at": "2020-05-29T00:59:08.000000Z",
        "updated_at": "2020-05-29T02:14:45.000000Z"
    },
    {
        "id": 2,
        "service_name": "Nails",
        "desc": "Nails Services",
        "image": "1590722173.jpg",
        "created_at": "2020-05-29T03:16:14.000000Z",
        "updated_at": "2020-05-29T03:21:09.000000Z"
    }
]

How I need the response:

[
    {
        "id": 1,
        "service_name": "Hair",
        "desc": "Everything that has to do with hair and more",
        "image": "https://google.com/avatars/1590713947.jpg",
        "created_at": "2020-05-29T00:59:08.000000Z",
        "updated_at": "2020-05-29T02:14:45.000000Z"
    },
    {
        "id": 2,
        "service_name": "Nails",
        "desc": "Nails Services",
        "image": "https://google.com/avatars/1590722173.jpg",
        "created_at": "2020-05-29T03:16:14.000000Z",
        "updated_at": "2020-05-29T03:21:09.000000Z"
    }
]

I tried the following way:

/**
 * Display a listing of the resource.
 *
 * @return \Illuminate\Http\Response
 */
 public function serv_list(){
   $services = Add_Service::all();

   foreach($services as $service){
      $id  = $service->id;
      $name = $service->service_name;
      $desc = $service->desc;
      $pic = $service->image;
   }
   $image = 'https://google.com/avatars/'.$pic;
   $data = array('id'=>$id, 'name'=>$name, 'desc'=>$desc, 'image'=>$image);
   return $data;
 }

The response is:

{
    "id": 2,
    "name": "Nails",
    "desc": "Nails Services",
    "image": "https://google.com/avatars/1590722173.jpg"
}
0

1 Answer 1

2

You have to use basic Laravel Transform for this.

$services->transform(function($q){
    $q->image = 'https://google.com/avatars/' . $q->image;
    return $q;
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.