I have a department table. Here is a column name created_by. It stores the id from users table. I want to call the users name from created_by column's id. But it shows error Column not found: 1054 Unknown column 'users.department_id' in 'where clause'
Department Model:
public function user(){
return $this->hasMany(User::class);
}
User Model:
public function department(){
return $this->belongsTo(Department::class, 'created_by');
}
Controller:
public function index(){
$departments = Department::where('deletion_status', 0)->orderBy('department', 'asc')->get();
return view('admin.department_manage', compact('departments'));
}
Blade file:
@foreach($departments as $row)
<tr>
<td>{{ $loop->iteration }}</td>
<td>{{ $row->user->name }}</td>
</tr>
@endforeach
Can anyone please help me to find out the solutions?
CodePudding user response:
you specified laravel wrong relationships. do this: for the user model departments() { return $this-> hasMany(Department::class, 'created_by')}
Then for the department model: user(){return $this->belongsTo(User::class, ' created_by', 'id')}.
The call would be: departments= Department::where('deletion_status', 0)->with('user')->get()
Each element in the departments collection will have information about a user. , which can be obtained for example like this department -> user->name