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');
}
The
$items_id
would be an array of ids, so theItem::find($items_id)
would returncollection
of Items that each Item has categories. So try to useeach
higher order messages:or simply: