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

781 Views Asked by At

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');
}
2

There are 2 best solutions below

7
On BEST ANSWER

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);
0
On
public function store(ItemsValidatorRequest $request)
{
    // Here the $items_id will be a collection of ids not a single one
    $items_id = Item::select('items_id')->latest()->get();

    //Here the $item will be a collection of Item records
    //Since you are passing an array/collection of id to the find
    $item = Item::find($items_id);

    //This will error out as collection of Item records do not have categories relation/method on it
    $item->categories()->attach($request->categories);
}

So try this

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