Home > OS >  Laravel hasOne returns empty object
Laravel hasOne returns empty object

Time:06-04

In my Laravel 8 application I two models, a User and Optout. My Optout model has a user_id column and a user is able to create an optout through a front-end form which populated this table with an entry with their user id.

On my User model when I try to create a relationship to get the optout I get an empty object instead of the data from my optout? Why? What am I missing?

/**
 * The accessors to append to the model's array form.
 *
 * @var array
 */
protected $appends = [
    'has_marketing_optout'
];

/**
 * Determine if the user is currently subscribed or not
 *
 * @return bool
 */
public function getHasMarketingOptoutAttribute()
{
    try {
      return $this->hasOne(Optout::class, 'user_id');
    } catch (\Exception $e) {
      return false;
    }
}

CodePudding user response:

You don't need attributes for it. You need to create a relationship.

public function output()
{
  return $this->hasOne(Optout::class);
}

Then you can access it like $user->output

If you want only one field from that relation you can define attribute.

/**
 * The accessors to append to the model's array form.
 *
 * @var array
 */
protected $appends = [
    'has_marketing_optout'
];

public function output()
{
  return $this->hasOne(Optout::class);
}


public function getHasMarketingOptoutAttribute()
{
    return $this->output->field_name;
}
  • Related