1

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

7
  • Where is foreach loop ? Do you have proper keys/fields in tables for making relation ? Commented Mar 13, 2014 at 21:08
  • Tried both in my controller and view: foreach ($invoice->line_items as $line_item) triggers the error. Commented Mar 13, 2014 at 21:16
  • Try dd($invoice->line_items) it's not an array but a scalar value. Commented Mar 13, 2014 at 21:21
  • 1
    Make sure the current invoice has a line_items, try using a different ID or try dd(Invoice::with('line_items')->get()) and check the result. Commented Mar 13, 2014 at 21:25
  • If I use the with keyword, it works. How come it does not without If I’ve set them up as per the Laravel docs? Commented Mar 13, 2014 at 21:29

3 Answers 3

7

change

public function line_items() 

for

public function lineItems()

and it will work , tested in Laravel 4.1 :)

Sign up to request clarification or add additional context in comments.

Comments

0

Check your tables relations... (Schema)

Your FK must be lineitem_id... You have modified this? Laravel will configure automatically... Don't change this...

Then, try

$invoice->line_items() or $invoice->line_items in 4.1

2 Comments

I think you misunderstand. Invoices has many LineItems, therefore my line_items table has a foreign key called invoice_id that links it to its parent invoice row.
I See. Sorry. try change name, line_items instance of lineItems() Maybe collisions.. ?
0

Check for line_items before the foreach loop:

if(! $invoice->line_items->isEmpty()){
    foreach($invoice->line_items as $line_item){
        //do stuff
    }
}

Also, it won't hurt to explicitly mention the FK, although laravel will automatically try to do it for you provided you use proper names for your table fields.

//Invoice Model
return $this->hasMany('LineItem', 'invoice_id');

//LineItem Model
return $this->belongsTo('Invoice', 'invoice_id');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.