Home > Mobile >  "BookInfo::type must return a relationship instance but null was returned"
"BookInfo::type must return a relationship instance but null was returned"

Time:08-13

First of all, this is my first Laravel project, it's just something I'm knocking together to learn, so please go easy on me.

Let's say I'm creating an application representing a library. Each Book has some info (BookInfo) about it, and each BookInfo contains a (reference to) a BookType that says if it's "fiction" or "non-fiction".

So if my BookInfo schema looks somewhat like:

//...
$table->unsignedBigInteger('book_id');
$table->unsignedBigInteger('book_type_id');

//...
$table->foreign('book_id')->references('id)->on('books');
$table->foreign('book_type_id')->references('id)->on('book_type');

And my BookType schema looks like this:

//...
$table->id();
$table->string('name');

What does the method on the BookInfo model look like that returns the BookType?

I've got this, and seem to have tried innumerable alternatives (with slightly different errors):

public function type()
{
    return BookType::where('book_type_id', $this->book_type_id)->get()->first();
}

And yes, I'm sure that the id I'm trying to lookup there exists in the book_type table. I actually only really want the ->name of the BookType but obviously I need to get the BookType first...

CodePudding user response:

public function type(): BelongsTo
{
    return $this->belongsTo(BookType::class, 'book_type_id');
}

OR if you change the method name to bookType you can omit the second argument to belongsTo because it will automatically resolve the foreign key based on the method name, and you can just do:

public function bookType(): BelongsTo
{
    return $this->belongsTo(BookType::class);
}

Here's the eloquent relationship reference from the Laravel docs: https://laravel.com/docs/9.x/eloquent-relationships

CodePudding user response:

in migration for foreign key use: $table->foreignIdFor(BookType::class, 'book_type_id');

  • Related