Marco
Marco

Reputation: 644

Returning string if object is empty in Laravel 5.4

This is my User model:

/**
 * The settings that belong to the user.
 */
public function settings()
{
    return $this->hasMany(Setting_user::class); 
}

/**
* Get user's avatar.
*/
public function avatar()
{
   $avatar = $this->settings()->where('id',1);

    if(count($this->settings()->where('id',1)) == 0 )
    {
        return "default-avatar.jpg"; 
    }

    return $this->settings()->where('id',1);
}

In my view I am accessing the value like that:

Auth::user()->avatar

When the user has an avatar everything is fine. But when is empty the method avatar() returns a string and I get the following error:

Relationship method must return an object of type Illuminate\Database\Eloquent\Relations\Relation (View: C:\xampp\htdocs\laravel\laravel-paper-dashboard\resources\views\dashboard\user-profile.blade.php)

Upvotes: 0

Views: 391

Answers (1)

Josh
Josh

Reputation: 1804

You may want to use an Eloquent Accessor instead.

public function getAvatarAttribute() {
    $avatar = $this->settings()->where('id',1)->first(); // Changed this to return the first record

    if(! $avatar)
    {
        return "default-avatar.jpg"; 
    }

    // You will need to change this to the correct name of the field in the Setting_user model.
    return $avatar->the_correct_key; 
}

This will allow you to then call Auth::user()->avatar in your templates.

Otherwise Eloquent thinks you're trying to get a relationship.

Upvotes: 2

Related Questions