BigJobbies
BigJobbies

Reputation: 4045

Laravel one-to-one relationship giving errors

Im trying to implement a one-to-one relationship, im calling it from a 'command' and i keep getting a Undefined property error when viewing any record in that relationship.

In my model i have the following

public function preferences()
{
    return $this->hasOne('App\WebsitePreferences', 'id', 'website_id');
}

Then im calling it as such

    $websites = Website::where('active', 1)->get();

    foreach ($websites as $website) {

        var_dump($website->preferences()->status);

    }

the exact error is as follows

Undefined property: Illuminate\Database\Eloquent\Relations\HasOne::$status 

If i do a var_dump($website) it returns all the values in that table, just not the ones in the WebsitePreferences table associated with that 'Website'

I have a few other one-to-one relationships and they all work just fine.

Any help would be greatly appreciated.

Upvotes: 0

Views: 55

Answers (3)

Parithiban
Parithiban

Reputation: 1656

public function preferences()
{
    return $this->hasOne('App\WebsitePreferences', 'id', 'website_id');
}


$websites = Website::where('active', 1)->get();

You need to check empty for relation

foreach ($websites as $website) {
     if(empty($website->preferences) === false){
       $website->preferences->status
    }
}

Upvotes: 0

Eliott
Eliott

Reputation: 262

In your model try this:

public function preferences()
{
    return $this->hasOne('App\WebsitePreferences', 'website_id');
}

In your controller:

Website::with('preferences')->get()

in your view:

 foreach ($websites as $website) {
     @php(dd($website->preferences->status)); }

Upvotes: 0

jeremy_nikolic
jeremy_nikolic

Reputation: 90

When you call a relationship as a method, it returns the QueryBuilder instance. This allow you to keep chaining with where, with and so on.

Instead you should call it as an attribute:

$website->preferences->status 

Upvotes: 1

Related Questions