Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/laravel/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
方法Illumb\Database\Eloquent\Collection::attach在laravel 8中不存在错误_Laravel_Laravel 8 - Fatal编程技术网

方法Illumb\Database\Eloquent\Collection::attach在laravel 8中不存在错误

方法Illumb\Database\Eloquent\Collection::attach在laravel 8中不存在错误,laravel,laravel-8,Laravel,Laravel 8,我试图为产品添加类别。我想在项目和类别之间创建一个表。我在控制器中创建了一个函数,将其发送到数据库。然而,当我想发送它时,我得到了以下错误,我不知道我能修复它。方法Illumb\Database\Eloquent\Collection::attach不存在 控制器: public function store(ItemsValidatorRequest $request) { if ($files = $request->image) { $

我试图为产品添加类别。我想在项目和类别之间创建一个表。我在控制器中创建了一个函数,将其发送到数据库。然而,当我想发送它时,我得到了以下错误,我不知道我能修复它。方法Illumb\Database\Eloquent\Collection::attach不存在

控制器:

public function store(ItemsValidatorRequest $request)
    {
        if ($files = $request->image) {
            $destinationPath = 'images';
            $profileImage = date('YmdHis') . "." . $files->getClientOriginalExtension();
            $files->move($destinationPath, $profileImage);
        }
        else {
            return redirect()->back()->with('warning', 'Mislukt');
        }
        $user = Auth::user()->id;

        Item::create([
            'user_id' => $user,
            'item_title' => $request->titel,
            'item_img' => $profileImage,
            'item_description' => $request->beschrijving,
            'item_price' => $request->prijs,
            'item_slug' => $this->slugify($request->titel)
        ]);

        $items = Item::latest()->get();
   

     // line where it goes wrong
        $items->each->categories()->attach($request->categories);

        return redirect()
            ->route('admin.items.index')
            ->with('success', 'Het item is toegevoegd aan je verlanglijst');
    }
我的模型:

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

Laravels
高阶函数调用,采用单个方法调用,而不是多个方法调用。因此,如果您在
类上创建一个helper方法,它将解决您的问题

class Item {
    public function attachCategories($categories) {
        $this->categories()->attach($categories);
    }
}
这样就可以这样分配类别

$items->each->attachCategories($request->categories);