B. All B. All - 1 month ago 6
PHP Question

Laravel 5.2 @foreach - invalid argument supplied

I'm trying to show data from 2 related database tables and I get the @foreach - invalid argument supplied error. does anyone know what I did wrong and know how to fix it?

Here is my Controller function

public function index()
{
return view('Voorraad.index', [
'voorraads' => Voorraad::all(),
'Products' => Producten::all()
]);
}


as u can see i have a model "voorraad" and "producten" its a 1:n relation in the database "producten" beeing the 1 side and "voorraad" beeing the n side of the relation between them,

This is my "voorraad" model

class Voorraad extends Model

// Model Voorraad has the attributes, Aantal and Id;

{
protected $fillable = ['voorraadId','aantal'];
protected $table = 'Voorraad';

public $timestamps = false;


/*
* Voorraad can have multiple products;
*
*/

public function Product()
{
return $this->HasMany('App\Producten', 'Producten_ProductenId');
}
}


This is my "Producten" model

class Producten extends Model
{

// model producten holdes the attribues naam, inkoopprijs, verkoopprijs,

protected $fillable = ['productId','naam','inkoopprijs','verkoopprijs'];
protected $table = 'Producten';

public $timestamps = false;


//producten Belongs to "voorraad"

public function voorraad()
{
return $this->belongsTo('App\Voorraad', 'producten_productenId');
}
}


and this is the view I want to display my database models on:

@foreach($voorraads as $voorraad)

<tr>
<td>{{$voorraad->voorraadId}}</td>
<td>{{$voorraad->aantal }}</td>
@foreach($voorraad->producten as $products)
<td>{{ $products->Naam }}</td>
<td>{{ $products->InkoopPrijs }}</td>
<td>{{ $products->VerkoopPrijs }}</td>
@endforeach
<td></td>
<td></td>
</tr>
@endforeach


This is the dd of $voorraads

This is my migration for the voorraad Table

public function up()
{
Schema::create('voorraad', function(blueprint $table)
{
$table->increments('id');
$table->string('naam');
$table->foreign('Locaties_Id')
->reference('Id')
->on('locaties')
->onDelete('cascasde');
$table->foreign('Producten_Id')
->reference('Id')
->on('producten')
->onDelete('cascade');
});
}


and this is my migrations for the producten table

public function up()
{
Schema::create('producten', function(blueprint $table)
{
$table->increments('id');
$table->decimal('inkoopprijs', '10, 2');
$table->decimal('verkoopprijs', '10, 2');
$table->foreign('Fabrieken_Id')
->reference('Id')
->on('fabrieken')
->onDelete('cascasde');
});
}

Answer

The problem lies within the Voorraad model, where you defined the relation:

public function Product()
{
   return $this->HasMany('App\Producten', 'Producten_ProductenId');
}

But in the view you try to access the relation by calling

@foreach($voorraad->producten as $products)

If you change the method in the model it should work

public function producten()
{
   return $this->HasMany('App\Producten', 'Producten_ProductenId');
}