-1

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();
    }
ibrar Adil
  • 21
  • 5
  • 2
    `$racks` is a collection of racks, not a single rack, so it won't have an ID. You'll have to iterate through each rack and get the count each. – aynber Feb 03 '22 at 13:39
  • I think what you actually want to do is `$racks = Rack::all()->with('books')` then you can iterate through `$racks` and check `$rack->books->count()` – miken32 Feb 03 '22 at 18:15
  • I just want to update books in racks according to their rack_id and count the number of books in each rack at the end – ibrar Adil Feb 03 '22 at 20:56
  • Correct syntax would be `Rack::with('books')->get()`; when you call `::all()`, it returns a `Collection`, which doesn't have a `with()` method . Note, this assumes you have a `hasMany` between `Rack` and `Book` models. – Tim Lewis Feb 03 '22 at 21:03

1 Answers1

0

You must to look for a concret $rack, not all $racks Collection:

$count = Book::where('rack_id', $racks[0]->id)->count();
entoniperez
  • 544
  • 5
  • 14