Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Hujjat's avatar
Level 10

How to relate Student with Class and Eloquent relationship

Hi, I get this error while try to show student's class in view.

'''

Call to undefined method Illuminate\Database\Query\Builder::belognsToMany() (View: 

'''

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
    {
        use Notifiable;

    /**
    * The attributes that are mass assignable.
    *
    * @var array
    */
    protected $fillable = [
    'name',
    'last_name',
    'father_name',
    'dob',
    'email',
    'password',
    'phone',
    'address',
    'admission_year',
    'gender',
    'photo',
    'class_id',
    'subject_id',
    'user_type'

    ];

    /**
 * The attributes that should be hidden for arrays.
 *
 * @var array
 */
protected $hidden = [
    'password', 'remember_token',
];

    public function grade(){
        return $this->belognsToMany('App\Grade');
 }
}

'''

and Here is my Grade model

'''

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Grade extends Model
{
public $table = 'classes';

protected $fillable = [
    'name',
    'fee',
    'limit'
    ];


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

}

'''

Maybe the relationship is the problem. But I don't know how to relate them. I can save the class id to users table and I want o show the class or grade name based on the ID I have saved on the database to view. But I get the error.

This is what I try in view that cause the problem

'''

{{$student->grade()->name}}

'''

Can anyone tell me what is wrong ?

Thank's :)

0 likes
13 replies
hlgrrnhrdt's avatar

Hi,

First of all you did not define a class relationship (maybe that is just a typo in your example).

public function class()
{
    return $this->belognsTo('App\Grade');
}

Then you would access the name property of the class through

$student->class->name

Or maybe this is completely wrong and you have to figure out what kind of relationship you want between user, grade (class?).

Hujjat's avatar
Level 10

Yep that's a typo, :) I have to try

$student->grade()->name

but it's not working either.

yansusanto's avatar

I think this should be the correct relationship

User Model (has many grade)

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

Grade Model (belongs to user)

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

Then

$grade->user->name
1 like
merlin334's avatar

If you have the class_id in user table, then one user can have only one grade.

public function grade(){
    return $this->hasOne(Grade::class, 'id', 'class_id');
}

Update: A better solution for this would be to use many to many relationship, so you can have many students in many classes.

You need to create a junction table named user_class with 2 fields, user_id and class_id, optional created_at, updated_at but specify ->withTimestamps()

https://postimg.org/image/cvbzd3kpl/

If you have laravel 4.2, instead of Grade::class use 'App\Grade' same for User::class - 'App\User';

// User.php
public function grades(){
    return $this->belongsToMany(Grade::class, 'user_class', 'class_id', 'user_id')->withTimestamps(); // only if you have created_at and updated_at in user_class
}

// Grade.php
public function users(){
    return $this->belongsToMany(User::class, 'user_class', 'user_id', 'class_id')->withTimestamps(); // only if you have created_at and updated_at in user_class
}

// TEST in controller
// Get all users with grades
$users = User::with('grades')->get()->toArray();

// Get all grades with users
$grades = Grade::with('users')->get()->toArray();
dd($users, $grades, $users->grade->name, $grades->user->email);
abusalameh's avatar

The problem with the name of the method

        return $this->belognsToMany('App\Grade');

it must be

return $this->belongsToMany(Grade::class);
// or 
return $this->belongsToMany('App\Grade');
1 like
Hujjat's avatar
Level 10

@merlin334 Thank's for your suggestion, But I want to use one to many relationship. I mean, a user has only one grade and a grade belongs to many users.

Hujjat's avatar
Level 10

@abusalameh Thank's for your respond. that was a typo mistake. I fixed that and still showing the same error. :(

merlin334's avatar
Level 10

Then use my first function.

Laravel 5

User.php

public function grade(){
    return $this->hasOne(Grade::class, 'id', 'class_id');
}

Grade.php

public function users(){
    return $this->belongsTo(User::class, 'id', 'class_id');
}

Laravel 4.2

User.php

public function grade(){
    return $this->hasOne('App\Grade', 'id', 'class_id');
}

Grade.php

public function users(){
    return $this->belongsTo('App\User', 'id', 'class_id');
}

I tested it locally. It works.

1 like
hlgrrnhrdt's avatar

That is not entirely correct

class User
{
    public function grade()
    {
        // One user belongs to one grade
        return $this->belongsTo('App\Grade');
    }
}

class Grade
{
    public function users()
    {
        // One grade has many users
        return $this->hasMany('App\User');
    }
}
willvincent's avatar

The specific cause of the error in the first post is due to this typo:

$this->belognsToMany

Should be

$this->belongsToMany

n and g are transposed.

Aside from that though.. shouldn't this be a many to many relationship, necessitating a pivot table? So both sides of the relationship should have a belongsToMany() defined?

I would assume students can belong to many classes, and classes 'belong to' (are made up of) many students. right?

In fact, I could see this even being more than a simple two-way relationship as a particular class might be offered multiple times/day but a student may be in the morning instance of that class, but not the mid-day or evening instances. Or the same class could be offered by multiple instructors, etc..

Certainly things can get very complex, very quickly. BUT -- the cause of the error message that started this thread is entirely due to a typo in the method name.

2 likes

Please or to participate in this conversation.