Home > front end >  Laravel. Property does not exist on this collection instance. Relation error
Laravel. Property does not exist on this collection instance. Relation error

Time:01-23

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 Model\Authors:

public function books () {
    return $this->hasMany('App\Models\Books');  
}

In Model\Books:

public function author() {
    return $this->belongsTo('App\Models\Authors'); 
}

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.

CodePudding user response:

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:

public function index () {
    
    $authors = Authors::latest()->first();; 
    dd($authors->books); 
     
}

CodePudding user response:

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:

public function index () {
    $authors = Authors::all(); 
    $authors->books->each(function ($book) {
      print_r($book);
    }
}

In case you want to retrieve the books of a single Author you can return a single model instance for the Author like:

public function index () {
    $author = Authors::where('id',1)->first(); 
    print_r($author->books);
}
  • Related