alexandre
alexandre

Reputation: 335

Laravel Eloquent belongsTo: "Trying to get property of non-object" when using without echo/die/var_dump

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

Upvotes: 0

Views: 5766

Answers (1)

alexandre
alexandre

Reputation: 335

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

Upvotes: 1

Related Questions