I want to count the number of books in a rack according to their id's
I'm getting this error
Property [id] does not exist on this collection instance.
controller
$racks = Rack::all();
$count = Book::where('rack_id', $racks->id)->first();
books table
Schema::create('books', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->unsignedBigInteger('rack_id')->nullable('true');
$table->foreign('rack_id')->references('id')->on('racks')->onDelete('cascade');
$table->string('author');
$table->year('published_year');
$table->timestamps();
});
racks table
Schema::create('racks', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->integer('books_count')->nullable('true');
$table->timestamps();
});
edit : I have tried the loop but nothing seems right to my coding skill
$racks = Rack::all();
$books = Book::all();
$length = count($books);
$count=0;
for($i = 0; $i<$length; $i++)
{
$count = Book::where('rack_id', $racks[$i]->id)->get();
}