Mubarak Awal
Mubarak Awal

Reputation: 489

Relationship method must return an object of type Illuminate\Database\Eloquent\Relations\Relation

I'm trying so create using Laravel eloquent relationship but I'm getting this error

Relationship method must return an object of type Illuminate\Database\Eloquent\Relations\Relation

This is what I'm trying to do in my controller

$data = $request->all();

    $company = Company::create([
      'name' => $data['name'],
      'description' => $data['description'],
    ]);

    $company->members->create([
        'name' => $data['name'],
        'email' => $data['email'],
        'status' => $data['status'],
        'password' => bcrypt($data['password']),
    ]); 

This is my Company Model

class Company extends Model
{
protected $fillable = [  'name', 'description'];

public function members(){
  $this->hasMany('App\User');
}

public function reports(){
  $this->hasMany('App\Report');
}
}   

This is my User Model

class User extends Authenticatable
{
use Notifiable;

protected $fillable = [
    'name', 'email', 'password', 'company_id','status',
];

protected $hidden = [
    'password', 'remember_token',
];


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

And this is the error I'm getting

(1/1) LogicException
Relationship method must return an object of type 
Illuminate\Database\Eloquent\Relations\Relation
in HasAttributes.php (line 403)
at Model->getRelationshipFromMethod('members')
in HasAttributes.php (line 386)
at Model->getRelationValue('members')
in HasAttributes.php (line 316)
at Model->getAttribute('members')
in Model.php (line 1262)
at Model->__get('members')
in AdminController.php (line 48)
at AdminController->addCompany(object(Request))
at call_user_func_array(array(object(AdminController), 'addCompany'), array(object(Request)))
in Controller.php (line 55)
at Controller->callAction('addCompany', array(object(Request)))
in ControllerDispatcher.php (line 44 )

How do I solve this error?

Upvotes: 1

Views: 2012

Answers (1)

Leo
Leo

Reputation: 7420

you have forgotten to return the relation like so :

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

public function members(){
    return $this->hasMany('App\User');
}

public function reports(){
    return $this->hasMany('App\Report');
}

Upvotes: 8

Related Questions