Laravel Eloquent Query using withCount and get([name as value])

Viewed 642

I have a problem in laravel when i am trying to retrieve records using withCount whilst wanting to return a field as a different name. If i remove the getCount the query will return the fields correctly however when i add in the withCount it will ignore the AS clause in the statement.

Maker::where('type_id', $request->type_id)->get(['maker_name AS label', 'id AS value']);

Correctly returns an array of objects with the props 'label' and 'value'

Maker::where('type_id', $request->type_id)->has('maker')->has('listing')->withCount(['listing'])->get(['maker_name AS label', 'id AS value']);

This statement ignores the AS clause and just returns the records from the database with the listing_count field added

What i want is the query to return:

[
   {
     label : 'string',
     value : int,
     listing_count : int
    },
    ...


]

1 Answers

You should try the below code

Maker::select(['maker_name AS label', 'id AS value'])->where('type_id', $request->type_id)->has('maker')->has('listing')->withCount(['listing'])->get();
Related