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

rojonunoo's avatar

Querying Relationship

I am new to Laravel and i have these relationship

public function fees(){

return $this->hasMany('App\Fees');

}

public function students()

{

return $this->belongsTo('App/Student');

}

public function up() {

Schema::create('students', function (Blueprint $table) {

    $table->engine = 'InnoDB';

    $table->increments('id');
    $table->string('name');
    $table->date('dob');
    $table->string('last_school_attended');
    $table->string('avatar')->default();
    $table->decimal('student_fees');
    $table->softDeletes('deleted_at');
    $table->timestamps();

});

}

public function up() {

Schema::create('fees', function (Blueprint $table) {
    $table->increments('id');
    $table->unsignedInteger('student_id')->unsigned();
    $table->string('payment_method');
    $table->string('bank_name')->nullable();
    $table->string('account_no')->nullabe();
    $table->decimal('balance');
    $table->decimal('amount');
    $table->date('date');
    $table->timestamps();


    $table->foreign('student_id')
        ->references('id')->on('students')
        ->onDelete('cascade')
        ->onUpdate('cascade');

});

I can get all values in the fees table but i cannot fetch the student name for e.g

public function index($fees)

{

$fees = Fees::FindorFail($fees);

//if fees_id = 1; 

i can fetch all data is that column but for the student_id i keep getting only the ID and i understand thats the value being stored . how do i get the student's actual name

}

i don't seem to figure out how to call it through the relationships i have set .

0 likes
7 replies
MWDeveloper's avatar

$fees->students->name;

//use the name of the method in the middle

rojonunoo's avatar

@MWDeveloper i tried that before .. but i just tried it and this is what am getting

1/1 .ErrorException in FeesController.php line 108: Trying to get property of non-object

rojonunoo's avatar

@MWDeveloper no that record isn't empty . if i should output the data from that specific coloumn in the database i can get the student_id . and i have checked the database too its not empty ..

MWDeveloper's avatar
Level 4

public function student()

{

return $this->belongsTo('App/Student'); }

in your fees module you should have the method student in a singular form not plural use student() instead of students()then do the following

$fees->student->name;

Please or to participate in this conversation.