1

I get data from database using this query

$cats = Category::with(['cat_trans' => function($q) use($lang){
        $q->where('lang_code', $lang);
    }])->with(['cat_prod' => function($query) use ($lang,$currency){
        $query->with(['pro_trans' => function ($q) use ($lang){
            $q->where('lang_code', $lang);
        }]);
        ////////////
        $query->with(['pro_price' => function ($q) use ($currency){
            $q->with('currency_code')->where('cur_code', $currency);
        }]);
        ///////////
    }])->whereHas('account_type', function($qr) use ($account_type){
        $qr->where('account_type_id', $account_type);
    })->get();

I'm trying to remove the empty objects from the result, when I tried this I got the following response

{
"1": {
    "id": 1,
    "parent_id": null,
    "order": 1,
    "name": "Moblie",
    "slug": "mobile-1",
    "created_at": "2018-07-08 09:41:08",
    "updated_at": "2018-07-08 10:30:17",
    "cat_trans": [
       {
         "id": 1,
         "category_id": 1,
         "field": "title",
         "value": "Mobile",
         "lang_code": "en",
         "created_at": "2018-07-08 09:51:59",
         "updated_at": "2018-07-08 09:51:59"
       },
       {
         "id": 2,
         "category_id": 1,
         "field": "desc",
         "value": "smart",
         "lang_code": "en",
         "created_at": "2018-07-08 09:52:41",
         "updated_at": "2018-07-08 09:52:41"
       },
       {
         "id": 12,
         "category_id": 1,
         "field": "slug",
         "value": "mobile-1",
         "lang_code": "en",
         "created_at": null,
         "updated_at": null
       }
    ],
   }
}

I want to remove the key "1" from all the responses.

I used unset to get this value using this code

foreach ($cats as $k) {
        if (count($k->cat_prod) == 0) {
            unset($cats[$va]);
        }
        $va++;

    }

Then I tried using array_values but it displays that I can just use array_values on an array not an object.

Saclt7
  • 377
  • 1
  • 8
  • 32
Nadin
  • 73
  • 1
  • 8

4 Answers4

1

You can remove key "1" by simply doing

array_values((array)$cats)

You were receiving error for this function like "Can Only be used on array" was due to Laravel Query returns object , so you just need to do type conversion on it.

Harsh Virani
  • 367
  • 3
  • 8
0

$cats->toArray() if u need either to convert object to array or convert with some specific conditions

0

Your output looks like JSON so you can do this to eliminate the 1:

json_encode( $cats->{1} );
MonkeyZeus
  • 20,375
  • 4
  • 36
  • 77
0

You can use laravel simple method mapWithKeys()

$cats = $cats->mapWithKeys(function ($item) {
    return $item > 2;
});
$keyed->all();
apokryfos
  • 38,771
  • 9
  • 70
  • 114