Home > Net >  Data for foreach loop returning empty yet there is data in the table laravel 8
Data for foreach loop returning empty yet there is data in the table laravel 8

Time:11-03

i want to display a product with all its attributes in a page.i am using for each loop to display the data using a variable I have defined in the relationship.the problem is after fetching the data its unable to display the data on the browser.i havent understood where i have gone wrong..kindly assist. the method in the controller

public function show($id)
{
    $merchadisedata=Merchadise::find($id);

        
    return view('backend.merchadise.productattributes')->with(compact('merchadisedata'));
}

the variable in the product model that defines the relationship,i have imported the productattributemodel class at the top

public function merchadiseattributes() 
{
    return $this->hasMany(Productattribute::class);
}

the foreach loop in the blade file that show the data

<table id="admindatatables" class="table table-bordered  display nowrap" width="100%">
    <thead class="thead-dark">
        <tr>
            <th>Product Name </th>
            <th>Attribute Size</th>
            <th>Attribute Stock</th>
            <th>Attribute Price</th>
            <th>Attribute Sku</th>
            <th>Attribute Status</th>
    </thead>
    <tbody>
        @foreach ( $merchadisedata->merchadiseattributes as $attribute)
            <tr>
                <td>{{ $attribute->merchads->merch_name }}</td>
                <td>{{ $attribute->productattr_size}}</td>
                <td>{{ $attribute->productattr_stock }}</td>
                <td>{{ $attribute->productattr_price}}</td>
                <td>{{ $attribute->productattr_sku }}</td>
                <td>{{ $attribute->productattr_status}}</td>
                
            </tr>
        @endforeach
    </tbody>
    
</table>

CodePudding user response:

The problem what you have is that Laravel cant find the relation because the index name from your Productattribute table is not id. it is product_id.

Then you have declare in the model the new index name like that:

return $this->hasMany(Productattribute::class, 'foreign_key', 'local_key'); means:

public function merchadiseattributes() 
{
    return $this->hasMany(Productattribute::class, 'product_id', 'id');
}
  • Related