erezt
erezt

Reputation: 411

Treating belongsTo() that returns null

I have a model (request) that returns customer object base on it's id, it's receiving the id from a different machine so I want to treat non-existent values (i.e. id that doesn't exist returning the eloquent as null).

so for:

public function customer()
{
    return $this->belongsTo('App\Customer', 'site_user');
}

I've tried the following:

public function getSiteUserAttribute()
{
    if (!$this->relationLoaded('customer')) {
        $this->load('customer');
    }

    return $this->getRelation('customer') ?: $this->nullCustomer();
}

and nullCustomer() :

private function nullCustomer()
{
    $nonExist = 'non-exist-customer';

    $siteUser = new \Illuminate\Support\Collection;
    $siteUser->first_name = $nonExist;
    $siteUser->last_name = $nonExist;
    $siteUser->email = $nonExist;

    return $siteUser;
}

Yet Laravel is returning an error I can't really make sense of:

Undefined property: App\Request::$site_user (View: /../../index.blade.php)`

it's obviously related to getSiteUserAttribute() which extrapolates site_user, but I can't understand what's the issue.

I can isset() for every place that this relation is called, but i'm working with a smart framework, so I doubt that would be the best practice.

Just to reiterate, I'm trying ot treat null belongsTo() that wouldn't break the view.

Upvotes: 4

Views: 80

Answers (3)

Jonas Staudenmeir
Jonas Staudenmeir

Reputation: 25906

As Murat Tutumlu said, you can't have a site_user attribute and a getSiteUserAttribute() accessor at the same time.

You can specify default values with withDefault():

public function customer()
{
    return $this->belongsTo('App\Customer', 'site_user')
        ->withDefault([
            'first_name' => 'non-exist-customer',
            'last_name' => 'non-exist-customer',
            'email' => 'non-exist-customer'
        ]);
}

Upvotes: 1

Murat Tutumlu
Murat Tutumlu

Reputation: 780

It seems site_user field and site_user attribute is mixed.

The easiest way to get rid of the confusion, rename the field as site_user_id

Upvotes: 1

Elisha Senoo
Elisha Senoo

Reputation: 3594

Rewrite nullCustomer() to return App\Customer not \Illuminate\Support\Collection: I have not tested it though.

private function nullCustomer()
{
    $nonExist = 'non-exist-customer';

    $siteUser = new \App\Customer;
    $siteUser->first_name = $nonExist;
    $siteUser->last_name = $nonExist;
    $siteUser->email = $nonExist;

    return $siteUser;
}

Upvotes: 1

Related Questions