Skip to content
Advertisement

How to specify Books and Authors relationship in Eloquent insertion?

I was figuring out how to insert a hasMany entry using Laravel 4

Author.php module

JavaScript

Book.php Module

JavaScript

My controller

JavaScript

I’m getting one null record on authors table which pointed to the book and other 3 record that I inserted here without any pointing to the book.

Advertisement

Answer

First off I believe this is wrong schema, since probably one author could write more than a single book.

So I suggest you define many-to-many (belongsToMany) relation for this instead.

Anyway here is solution to your problem:

JavaScript

Another suggestion: rename the relation to authors so it is meaningful and you won’t catch yourself trying to treat it like a single model (while it always returns the Collection)

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement