Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel belongsTo relationship - Trying to get property of non-object

User.php

class User extends Authenticatable
{
    public function company() {
        return $this->belongsTo('App\Company');
    }
}

Company.php

class Company extends Model
{
    public function users() {
        return $this->hasMany('App\User');
    }
}

Table users

id name companies_id

Table companies

id name

I'm trying to get the name of the company attached to the user.

$user = User::findOrFail(Auth::user()->id);
$companyName = $user->company()->first()->name;

I got this error message Trying to get property of non-object

I don't get what I'm missing... Thank you in advance

like image 310
Léo Coco Avatar asked Apr 06 '17 20:04

Léo Coco


People also ask

How do you handle Trying to get property of non objects?

Trying to get property of a non-object Errorforeach($po_items as $item){ if(is_null($item->vendor_company)){ continue } // do what you want with the vendor & vat_no. } A third option would be to query only the items that have a vendor company, assuming that there is a relationship involved in there.

What does Trying property of non objects mean?

The error occurs when you try to access a property of an object that isn't an object. In this case you cannot access the property, as the $result isn't an object. It is a boolean = false. One thing is to check that a variable is an object using PHP's is_object.


1 Answers

By default, Eloquent is taking the name of the relationship + '_id' to guess the foreign key.

Solution A

public function company() {
    return $this->belongsTo('App\Company', 'companies_id')
}

Solution B

public function companies() {
    return $this->belongsTo('App\Company')
}
like image 119
Léo Coco Avatar answered Sep 28 '22 09:09

Léo Coco