I’m having an issue with relations in two of my models in a Laravel application. My models are:
class Invoice extends Eloquent {
protected $table = 'invoices';
public function line_items()
{
return $this->hasMany('LineItem');
}
}
And:
class LineItem extends Eloquent {
protected $table = 'line_items';
public function invoice()
{
return $this->belongsTo('Invoice');
}
}
In my controller, I fetch an Invoice row with the following:
$invoice = Invoice::find($id);
However, if I try and access the line_items property to fetch the LineItem rows relating to my invoice, I get the following error:
Invalid argument supplied for foreach()
Why is this? I’ve set my models up as per Laravel’s documentation: http://laravel.com/docs/eloquent#one-to-many
foreachloop ? Do you have proper keys/fields in tables for making relation ?foreach ($invoice->line_items as $line_item)triggers the error.dd($invoice->line_items)it's not an array but a scalar value.line_items, try using a differentIDor trydd(Invoice::with('line_items')->get())and check the result.withkeyword, it works. How come it does not without If I’ve set them up as per the Laravel docs?