Boubou
222
15
Laravel

Passing values form related tables to blade

Posted 1 year ago by Boubou

Hi,

I am struggling on this.

I have user model with:

public function role()
   {
      return $this->belongsTo('App\Role');
   }


   public function hasRole(){

   return optional($this->role)->name;

 }

An AdminController with

use App\User;
use App\Role;

    public function index()
    {
    $users = DB::table('users')->get();

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

    }

In My users-view.blade.php I have

                      @foreach ($users as $user)
                      <tr>
                      <td class="col-md-1">{{ $user->id }}</td>
                      <td class="col-md-2">{{ $user->username }}</td>
                      <td class="col-md-1">{{ $user->name }}</td>
                      <td class="col-md-2">{{ $user->surname }}</td>
                      <td class="col-md-2">{{ $user->email }}</td>
                      <td class="col-md-1">{{ $user->town_id }}</td>
                      <td class="col-md-1">{{ $user->isactivated }}</td>
                      <td class="col-md-1">{{ $user->role->name }}</td>
                      <td class="col-md-1"><button class="btn btn-success" type="submit">Activated</button></td></td>
                      <td class="col-md-1"><button class="btn btn-warning" type="submit">Edit</button></td>
                      <td class="col-md-1"><button class="btn btn-danger" type="submit">Delete</button></td>
                      </tr>
                      @endforeach 

All the data from the $user" is outputting correctly in the table apart from {{ $user->role->name }} I was expecting the role name of the user to be passed via {{ $user->role->name }}

I have 2 tables, users with "role_id" and roles with "id" and "name"

Any idea why I do not get any data on the {{ $user->role->name }} please?

Thank you.

Please sign in or create an account to participate in this conversation.

Reply to

Use Markdown with GitHub-flavored code blocks.