Saurabh Gupte
Saurabh Gupte

Reputation: 250

How to get a value from other table if it has one to many relation in Eloquent laravel 6?

I have 2 tables.

 1. Staff <br/>
    id | fname | lname | department

 2. Department<br/>
    id | name

There is a relation between Staff and Department. Department has many staff and Staff have a one department. Now I am trying to fetch data of staff. So instead of department in Staff table I should get name from department table.

Here is my model - Staff Model

class Staff extends Model
{
    protected $table = 'staff';

    protected $fillable = ['fname', 'lname', 'department'];

    function departments(){
        return $this->belongsTo(Department::class, 'department');
    }
}

And - Department Model

class Department extends Model
{
    protected $table = 'departments';

    protected $fillable = ['name', 'updated_at'];

    function staff(){
        return $this->hasMany('App\Staff', 'department');
    }
}

In my controller, I am trying to fetch all staffs but I am getting department's id. I need a name of that department. How can it be possible?

Thank you in advance.

Upvotes: 0

Views: 655

Answers (1)

Abhishek Honrao
Abhishek Honrao

Reputation: 835

As it has one to many relationship department, you need to change staff model Check -

class Staff extends Model
{
    protected $table = 'staff';

    protected $fillable = ['fname', 'lname', 'department'];

    function departments(){
        return $this->belongsTo(Department::class, 'id');
    }
}

And now if you wanna fetch all staff info.

In your controller -

public function index(){
 $data = Staff::with('departments')->find(1);
return $data->departments->name;
}

Hopefully it will work.

Upvotes: 2

Related Questions