Ad

Call To Undefined Relationship [users] On Model [App\Team] Laravel 6

- 1 answer

Hey i am pretty new in coding and laravel.I am trying to build an app here i think i messed it up but cant find a way around it.I am getting Call to undefined relationship [users] on model [App\Team] exception . I have two tables with many to many relationship . I want to show in the view "viewteams.blade.php" the teams that a user belongs to.

My User model

    public function users(){
      return $this->belongsToMany(Team::class);
    }

My team model

  public function teams(){
    return $this->belongsToMany(User::class);
  }

my Route

Route::get('/viewteams','[email protected]');

my ViewTeamController

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Team;
use App\User;

class ViewTeamController extends Controller
{
    public function index()
    {
      $teams = Team::all()->load('users');
      return view('teams.viewteams',compact('teams'));
    }
}

my viewteams.blade.php

@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-8">
            <div class="card">
                <div class="card-header"><h2 style="text-align:center;">Your Teams</h2></div>
                @foreach ($teams as $team)
                  @foreach($team->users as $user)
                    {{$user->org_name}}
                    @endforeach
                @endforeach

                <div class="card-body">

                </div>
            </div>
        </div>
    </div>
</div>
@endsection
Ad

Answer

Error means what relationship are you calling does not exist in that model.

User model is related to teams. You have given correct relationship but the function name is wrong.

In User.php table your function name should be teams and

In Team.php file, your function name should be users

User model

public function teams(){
  return $this->belongsToMany(Team::class,'team_user','users_id','teams_id');
}

Team model

  public function users(){
    return $this->belongsToMany(User::class,'team_user','teams_id','users_id');
  }

Controller.

public function index()
{
  $teams = Team::with('users')->get();
  return view('teams.viewteams',compact('teams'));
}
Ad
source: stackoverflow.com
Ad