Emkrypted
Emkrypted

Reputation: 67

Relationships with Laravel

I do not know why, but the result that I am getting it's empty... I am trying to make a relation between a supervisor and a branc_office.

The branch_office just has one supervisor. The supervisors can have many branch_office to manage.

So the relation it's 1 to Many.

My tables are:

The id_supervisor and id_user make the relation between them.

id_supervisor(foreign key) ----- id_user(primary key)

My models:

User.php

use Notifiable;

protected $primaryKey = 'id_user';

/**
 * The attributes that are mass assignable.
 *
 * @var array
 */
protected $fillable = [
    'full_name', 'email', 'password',
];

/**
 * The attributes that should be hidden for arrays.
 *
 * @var array
 */
protected $hidden = [
    'password', 'remember_token',
];

 /**
 * Get the comments for the blog post.
 */
public function branch_offices()
{
    return $this->hasMany('App\Branch_Office', 'id_supervisor');
}

Branch_office.php

protected $table = 'branch_offices';

protected $primaryKey = 'id_branch_office';

/**
 * Get the post that owns the comment.
 */
public function supervisor()
{
    return $this->belongsTo('App\User', 'id_user');
}

In the controller I am doing this:

$branch_office_detail = Branch_Office::find(1)->supervisor()->first();

but it displays a null or empty result... and there is a branch_office with id = 1

So I wonder, what it's wrong? becaiuse I have done this step by step and It's not working.

Thanks.

Upvotes: 0

Views: 62

Answers (1)

protected $table = 'branch_offices';

protected $primaryKey = 'id_branch_office';

public function supervisor()
{
    return $this->belongsTo('App\User', 'id_supervisor', 'id_user');
}

In almost all relationships the first param is the model, the second the foreign key, the third the local key. Also the the belongsTo function only return one record or null, you dont need to use first()

BranchOffice::find(1) returns the Branch;

BranchOffice::find(1)->supervisor returns the supervisor of the branch 1

BranchOffice::with('supervisor')->find(1) return the office with the supervisor

Upvotes: 1

Related Questions