Farshad
Farshad

Reputation: 2000

Manipulating Laravel resource API showing relation in comma separated format

I have a simple relation in a laravel resource as below :

In my home model :

public function gallery()
{
    return $this->hasMany(Gallery::class);
}

And in my gallery model :

public function home(){
    return $this->belongsTo(Home::class);
}

And now here in my controller :

$data = Home::with('gallery')
    ->where('is_deleted', 0)->Paginate(env('PAGINATE_NUMBER'));
return new HomeResource($data);

Now this shows me the result like below :

 {
        name: example,
        id: 1,
        gallery: {
            id: 1,
            name:item1,
        },
        {
            id: 2,
            name:item2,
        },
        {
            id: 3,
            name:item3,
        }
    }

But in my resource I want to change the format to something like below :

{   
name:example,
id : 1,
some other fileds ,
     gallery: {item1,item2,item3,item4,. . .
}
}

I want my gallery to select just the name column and show them comma separated but my problem is that I have to load relation in resource and change that I don't know if that is possible to change the attributes in relation loaded in resource or not .

Upvotes: 0

Views: 277

Answers (1)

Ahmed Atoui
Ahmed Atoui

Reputation: 1556

you can do this stuff on HomeResource with implode method :

class HomeResource extends JsonResource
{
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'gallery' => $this-> gallery->implode('name',','),

        ];
    }
}

Upvotes: 2

Related Questions