Search code examples
phplaravelframeworkslaravel-5eager-loading

Eager Loading in Laravel 5.2 is not working


I researched related to this question but didn't work on my situation. I'm studying Laravel 5.2 for now to learn my first framework. But I encountered this problem in the tutorial which is using "Eager Loading".

I'm not sure if Card Model and Table are needed but just to make sure I added them.

What I'm trying to do? I want to display the user that is associated with the note.


These are my codes and files

CardsController.php

public function show(Card $card)
{

    return $card->notes[0]->user;

}

TABLES:

User

    Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->string('username')->unique();
        $table->string('email')->unique();
        $table->string('password');
        $table->timestamps();
    });

Notes

Schema::create('notes', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id')->unsigned()->index();
            $table->integer('card_id')->unsigned()->index();
            $table->text('body');
            $table->timestamps();
        });

Cards

Schema::create('cards', function (Blueprint $table) {
        $table->increments('id');
        $table->string('title');
        $table->timestamps();
    });

MODELS: namespace and use are just the same to the other models that are blank

User.php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    public function User()
    {
        return $this->belongsTo(Note::class);
    }
}

Note.php

class Note extends Model
{
    protected $fillable = ['body'];

    public function card()
    {
        return $this->belongsTo(Card::class);
    }
}

Card.php

class Card extends Model
{
    public function notes()
    {
        return $this->hasMany(Note::class);
    }

    public function addNote(Note $note)
    {
        return $this->notes()->save($note);
    }
}

Expected Output:

Expected Output Image

My Output:

My output is blank. The browser didn't show anything.


Let me know if you see a missing code coz I shortened the CardsController.php because I think that code is the important.


Solution

  • Suddenly pop-up in my mind while thinking of the solution. This solved my problem. I just added the code below in User.php model. And it worked like magic.

     public function User()
        {
            return $this->belongsTo(Note::class);
        }