Home > Back-end >  Table relatioship laravel
Table relatioship laravel

Time:01-05

I am doing a laravel project and I have to list users information.

I have the follwing tables in my phpmyadmin

table users

=======Users========
=     id    =  1   =
=    name   = test =
= office_id =  1   =
====================

Table Officies

========offices========
=      id     =   1   =
=     name    = admin =
= description =  ...  =
=======================

I have the following controller:

   public function users()
    {

        $users = User::all();
        $offices = Office::all();

        return view('admin.users')->with(['funcionarios' => $users,
            'offices => $offices
        ]);
    }

The following route:

Route::get('/admin/users', [\App\Http\Controllers\FuncionariosController::class,'users'])->name('admin.users');

The following HTML:

<table >
    <thead >
    <tr>
        <th scope="col">ID</th>
        <th scope="col">Name</th>
        <th scope="col">office</th>
    </tr>
    </thead>
    <tbody>
    @foreach($users as $user)
        <tr >
            <th scope="row">{{$funcionario->id}}</th>
            <td><a style="cursor:pointer;" 
                   data-id="{{$user->id}}">
                    {{$user->name}}
                </a></td>
            <td>{{$user->office_id}}</td>
        </tr>
    @endforeach
    </tbody>
</table>

I want, instead of showing the office id,

 <td>{{$user->office_id}}</td>

the office table name. How can I achive this? I have used an if with a for each to achieve this, but is looks really cheap and not properly done.

CodePudding user response:

Add relationship in User model

public function office(){

   return $this->belongsTo(Office::class);
}

and in your controller

 $users = User::with(['office'])->get();

and in your view

<td>{{optional($user->office)->name}}</td>

if you need only those users who has office assigned then

 $users = User::has('office')->with(['office'])->get();
  • Related