'How to get mapping records as comma separated values in Laravel Eloquent
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'}

Solution 1:[1]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
