I am writing a searchable table which includes the area and population. Here is the basic query:
public function getCountryData()
{
$co = DB::table('countries')->leftJoin('country_detail','country_detail.country_id','=','countries.id')->addSelect(['countries.id','countries.name','country_detail.capital','country_detail.area','country_detail.iso3','country_detail.population','country_detail.currencyName','country_detail.phone','country_detail.continent'])->get();
return Datatables::of($co)
->addColumn('action', function($co){
$btn = '<div style="float:right">
<a href="'. route('country.edit',$co->id) .' " class="btn btn-outline-secondary btn-xs" title="edit" style="margin-right:.5em">'.getEditIcon().'</a><a href="'. route('country.show', $co->id) .'" class="btn btn-outline-secondary btn-xs" title="images" style="margin-right:.5em">'.getBinoculars().'</a>';
return $btn;
}) ->rawColumns(['action'])
->make(true);
}
All this works fine in my view except that the population field, for example, returns something like 29121286 and of course I want to format it so it is 29,121,286.
Can this be done in the query or something in Datatables itself?
Instead of formatting the number on client side using javascript, I suggest using php's number_format
function to format your number.
return Datatables::editColumn('population', function($item) {
return number_format($item->population);
});
For more help on formatting numbers, see https://www.php.net/manual/en/function.number-format.php