-2

It is my code in which I get the subcategories' names. But the problem is it shows data in an array form.

$couponCategory = Coupon::select('categories')->where('expiry_date', '>', $dt)->where('status', 1)->first();
$couponsCat = explode(',', $couponCategory);

$categoriesDetails = Category::select('category_name')->whereIn('id', $couponsCat)->whereNotIn('parent_id', [0, 0])->get()->toArray();
str_replace("'", "\'", json_encode($categoriesDetails));

echo "<pre>";
print_r($categoriesDetails);
die;

Result

Array
(
    [0] => Array
        (
            [category_name] => Casual T-Shirts
        )

    [1] => Array
        (
            [category_name] => Formal T-Shirt
        )

)

I also try to convert it into a string but the output is like

[{"category_name":"Casual T-Shirts"},{"category_name":"Formal T-Shirt"}]

I want the result just display the name Casual T-Shirts and Formal T-Shirt no brackets or anything in string formate

shaedrich
  • 5,457
  • 3
  • 26
  • 42
Muqadar Ali
  • 57
  • 2
  • 11

2 Answers2

1

You can use pluck to get just the field you want in a basic array format:

$categoryNames = Category::whereIn('id', $couponsCat)
  ->whereNotIn('parent_id', [0, 0])
  ->pluck('name');

Then loop over the results, either using blade of plain old PHP.

@foreach ($categoryNames as $name)
  {{ $name }}
@endforeach

foreach ($categoryNames as $name) {
  echo $name;
}
Peppermintology
  • 9,343
  • 3
  • 27
  • 51
0

Laravel collections can be imploded easily:

echo $categoriesDetails->map->category_name->join(' ');
shaedrich
  • 5,457
  • 3
  • 26
  • 42