I try to create relations between different tables in my database and get data from these tables, but I got an error: Property does not exist on this collection instance.
This is my code:
Migrations files:
Schema::table('books', function (Blueprint $table) {
$table->foreignId('author_id')->constrained('authors')->onUpdate('cascade')->onDelete('cascade');
});
In ModelAuthors:
public function books () {
return $this->hasMany('AppModelsBooks');
}
In ModelBooks:
public function author() {
return $this->belongsTo('AppModelsAuthors');
}
In AuthorsController:
public function index () {
$authors = Authors::all();
return dd($authors->books);
}
In BooksController:
public function index () {
$books = Books::all();
return dd($books->author);
}
If someone has an idea how to fix this, I will be very grateful.
4
Answers
Thank you guys! In my case, the right solution was :
In model:
And in controller :
And in view file I added:
Thank you again. The topic can be closed )))))
Your models is right but you wrong when you call $authors->books because $authors is collection of your Authors model not object of Author. If your want check your relationship you can do with this example:
Your relation between Authors and books is one-to-many so an Author
hasMany
books (like you have correctly stated in the model relation).The output of this is a collection so you can not access it that way, instead you need to loop it like:
In case you want to retrieve the books of a single Author you can return a single model instance for the Author like:
If you want to have all authors with their books, use eager loading
with()
If you wants all the books with their respective author
When you iterate the collection (like an array) in your blade, you can then access the relation
If you just want to get a dd of the books of one author you can do it like this