Search code examples
laravellaravel-8laravel-collection

Collection doesn't exist while trying to send data to two tables in Laravel 8


I was trying to add categories to products. I want to do it with a couple of tables between items and categories. I made a function in my controller to send it to the database. However, when I want to send it, I get the following error, and I don't know I can fix it.

Method Illuminate\Database\Eloquent\Collection::does not exist

Controller

public function store(ItemsValidatorRequest $request)
{
    $items_id = Item::select('items_id')->latest()->get();
    $item = Item::find($items_id);
    $item->categories()->attach($request->categories);
}

Model

public function categories()
{
    return $this->BelongsToMany('App\Models\Category');
}

Solution

  • The $items_id would be an array of ids, so the Item::find($items_id) would return collection of Items that each Item has categories. So try to use each higher order messages:

    $items_id = Item::select('items_id')->latest()->get();
    $items = Item::find($items_id);
    $items->each->categories()->attach($request->categories);
    

    or simply:

    $items = Item::latest()->get();
    $items->each->categories()->attach($request->categories);