Search code examples
phplaravelforeacharchitectureentity-attribute-value

Eav model , Foreach Loops


I'm creating a car-seller website. I have a car_properties table to store my car properties, such as ABS, Climate, Navigation, Alarm, etc.

I'm using EAV model for car properties table, so my table looks like:

id , name , value 

and keeps data like:

name : ABS ,     value : 1 
name : climate , value : 1

On show-single-car view, I'm displaying them. The problem is I'm using lots of foreach loops. On the same show-single-car view page, I have multiple areas to show these properties. Some of them are at the right side of the page, some of them at the bottom.

Is it true to use it this way, or can I fetch them without foreach? I don't feel good when using a lot of foreach loops.

my method :

public function showcar($id)
{
    $car = CarSale::findOrFail($id);
    return view('frontend.product')->with('car' , $car);
}

my view :

 @foreach( $car->carproperty as $property)                  
    {{ $property->name }} - {{ $property->value }}                                 
  @endforeach

Solution

  • Since you are not looping over the database access part of this, the loops you have are nothing but constructs used to render your UI, which IMO are perfectly safe and should present no issues performance- or maintenance-wise.

    The model(s) being rendered exists very briefly in memory in order for their data to be accessed and rendered by the framework.