Search code examples
phplaravel-5belongs-to

laravel 5.2 belongsTo relation not work


I'd like to get some additional user information from the divisions table.

But not work why?

BadMethodCallException in Macroable.php line 81: Method division does not exist.

class AdminsController extends Controller

public function getUserIndex()
{
  $users = User::all()->division();
  dd($users);
}

class User extends Authenticatable

public function division()
{
  return $this->belongsTo('App\Division', 'division_id');
}

class Division extends Model

public function users()
{
  return $this->hasMany('App\User');
}

Users table

$table->foreign('division_id')->references('id')->on('divisions')->onUpdate('cascade');

Divisions table

$table->increments('id');

Solution

  • The division() relationship is defined for each individual table row. By calling it on all(), you're attempting to get the relationship for all rows.

    You should be able to use something like:

    public function getUserIndex()
    {
        $users = User::all();
        foreach ($users as $user) {
            dd($user->division());
        }
    }