1

I have 5 columns in my database. Here are the names of the columns:

  • promo1
  • promo2
  • promo3
  • promo4
  • promo5

I would like to combine these columns to be able to make a foreach in my view.

I tried this:

$promos = Building::select('promo1', 'promo2', 'promo3', 'promo4', 'promo5')->where('id', $card->id)->get()->toArray();

and in my view :

@foreach($promos as $promo)
    <span>{{ $promo['promo1'] }}</span>
@endforeach

But I have only one result for my foreach. Instead of 5. And I can only select one by one ($ promo ['promo1'], $ promo ['promo2']) so doing a foreach would not help

Is there a way to do that? thank you very much

2 Answers2

0

When you're using get() method, you're getting a collection. Use the find() method to get an object instead of collection:

$promos = Building::select('promo1', 'promo2', 'promo3', 'promo4', 'promo5')->find($card->id)->toArray();

Then you'll be able to iterate over promos:

@foreach ($promos as $promo)
    <span>{{ $promo }}</span>
@endforeach
Alexey Mezenin
  • 158,981
  • 26
  • 290
  • 279
0

First get the building object

$building = Building::select('promo1', 'promo2', 'promo3', 'promo4', 'promo5')->findOrFail($card->id);

then loop through the promos

@foreach ($building->getAttributes() as $key => $value)
    <span>{{ $key }} : {{ $value }}</span>
@endforeach

note: using the $key here is optional

lucidlogic
  • 1,814
  • 13
  • 15