0
votes

I am trying to get mapping table data as comma separated in laravel eloquent.

In controller I have list function

public function list(Request $request){
    
    // $data = Application::all();
    $pagelimit = $request->pagelimit ?? 10;
    $data = Application::search(($request->input('query')?$request->input('query'):''))->with('technology.technologyInfo');
    if($request->status === 'ACTIVE')
            $data = $data->where('status', 'ACTIVE');
            $data = $data->orderBy('id','desc');
    if(!$request->pagelimit)
            $data = $data->get();
    else
        $data = $data->paginate($pagelimit);

    return $this->json_response('success', 'data fetched', $data);
}

then in application model (Application)

public function technology()
    {
        return $this->hasMany('App\Models\ApplicationTechnology', 'application_id', 'id');
    }

then in mapping model (ApplicationTechnology)

namespace App\Models;
use Illuminate\Database\Eloquent\Model;

class ApplicationTechnology extends Model
{
    protected $table = 'application_technology';

    public function technologyInfo()
    {
        return $this->hasMany('App\Models\Technology', 'id','technology_id');
    }
}

The above coding gives result with mapping data(technology_info) in new row,But I want this column as comma separated Like 'technology_info' : {'PHP', 'JAVA', 'Python'} enter image description here

1

1 Answers

1
votes

try pluck() and join() `

in ApplicationTechnology.php

protected $appends = ['technology_info_with_comma']; //https://laravel.com/docs/8.x/eloquent-serialization#appending-values-to-json


public function getTechnologyInfoWithCommaAttribute()
{
    return $this->technologyInfo()->pluck('name')->join(',');
}

ref link

https://laravel.com/docs/8.x/collections#method-pluck

https://laravel.com/docs/8.x/collections#method-join