A table row displayed data value instead of the department names. I tried to do some reading at the laravel website and found that this topic is under Eloquent:Relationships and thus have tried to implement it on my models. If I just use {{ $data->department }}, that allows me to retrieve the data but I got the value, an integer that corresponds to the department category on the table. But when I use {{ $data->Department->department }}, it got me an error Undefined property: stdClass::$DepartmentHowever, it seems like it's not working out. I think that I got some gaps in my knowledge. Please help. In a very tight schedule, I need to complete this project by tomorrow.
Data that I want to retrieve
<tbody >
@foreach($info as $data)
<tr>
<td >
<div >
<div >
{{ $data -> staff_id }}
</div>
</div>
</td>
<td >
<div >{{ $data -> name }}</div>
</td>
<td >
<div >{{ $data -> email }}</div>
</td>
<td >
{{ $data->Department->department }}
</td>
@endforeach
@if (auth()->user())
<td > <a href="/profile"> View profile </a></td>
@endif
<td ></td>
<td ></td>
<td ></td>
<td > <a href="/profile/edit/{{ Auth::user()->id }}">Edit </a></td>
</tr>
</tbody>
To use Department, I created a new function and put it on all my 4 models, to see that it may works. But in this case it didn't.
public function Department()
{
return $this->belongsTo(Department::class, 'department');
}
The page of the data that I shown previously is in AdminController and the route is,
Route::get('staffrecord', [AdminController::class, 'index'])->middleware('auth');
$data query in AdminController
<?php
namespace App\Http\Controllers;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class AdminController extends Controller
{
public function index()
{
$info = DB::table('users')->get();
return view('staffrecord', compact('info'));
}
}
Do I have to create a new model that corresponds to AdminController ? If it is, how should I name it ?
CodePudding user response:
you need to call the relationship with the query:
$info = User::with('department')->get() ;
this should work.