0

I've just started with Laravel and Eloquent. In my "Receipt"-model, I try to get information about a relationship. As long as I'm using var_dump, I get my information. As soon as I'm just returning the value to use it in a blade view, I get my "Trying to get property of non-object".

<?php

class Receipt extends Eloquent  {
    public function businesspartner()  {
        return $this->belongsTo('Businesspartner', 'f_businesspartner_id');
    }

    public function brand()  {
        return $this->belongsTo('Brand', 'f_brand_id');
    }

    public function invoice()  {
        return $this->belongsTo('Invoice', 'f_invoice_id');
    }

    public function name()  {
        $name = '';

        $bp = $this->businesspartner()->first();

        $name = $bp->salutation; // line 21
        $name .= ' ';
        $name .= $bp->lastname_company;


        return $name;
    }
}

The error occurs in line 21.

When I now put a var_dump($name);die(); before returning, it prints me my name.

What's going wrong here? :(

Regards, Timo

alexandre
  • 286
  • 3
  • 17
  • You're doing it in a loop, right? Check this http://stackoverflow.com/a/23911985/784588 – Jarek Tkaczyk Jan 05 '15 at 08:44
  • That's great. I was really sure that this can't be null, but my loop was already one step ahead when this error occured. With putting a `if(count($this->businesspartner))` around my $name building code lines, my problem is solved. All my debug outputs just stopped the code one iteration before, when still everything was ok. Can you provide your tip as an answer so I can accept this answer and mark this thread as solved? – alexandre Jan 05 '15 at 08:49
  • No need, just upvote the linked answer. – Jarek Tkaczyk Jan 05 '15 at 09:51
  • Not possible yet for me, need 15 reputations first ;-) Just created my account here. – alexandre Jan 05 '15 at 10:22

1 Answers1

1

SOLUTION

As @Jarek Tkaczyk wrote, I was calling the name() method in a loop.

When doing my debug outputs, I got data from my first row. When getting the error, the code was already processing the second row, where the foreign key was null.

Wrapping the problematic part in if(count($this->businesspartner)) helped.

For more information about that, Jarek linked that post: https://stackoverflow.com/a/23911985/784588

Community
  • 1
  • 1
alexandre
  • 286
  • 3
  • 17