2 years ago

ORM select model with related data and view

Posted 2 years ago by baguus

Hi I've been battling the next orm fight. I want to show data from 3 related tables. user, roles, companies and role_user pivot table.

User model

public function roles() {
    return $this

public function Companies() {
    return $this->belongsTo(Companies::class, 'id');

Role model

public function users() {
    return $this

Companies model

public function User() {
        return $this->hasMany(User::class, 'companies_id');


public function show(Request $request, $id) {

// $user = User::findOrFail($id); <- gets data from user model without companies and roles

// nth attempt..
$user = User::with('roles','companies')->findOrFail($id);

// How do I retrieve/add/join data from companies and roles for specific user?

return view('users.view', compact(['user']));


Username: {{ $user->username }}

Email: {{ $user->email }}

Company: {{ $?????->????->company_name  }}

Roles: @foreach ($????? as $role)
{{ $role->name  . ',' }}

How to correctly add/append the related data and print it out on view? Thank you

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