【问题标题】:Method Illuminate\Database\Eloquent\Collection::attach does not exist error in laravel 8方法 Illuminate\Database\Eloquent\Collection::attach 在 laravel 8 中不存在错误
【发布时间】:2021-03-19 14:07:20
【问题描述】:

我试图为产品添加类别。我想用项目和类别之间的一对表来做到这一点。我在控制器中创建了一个函数将其发送到数据库。但是,当我想发送它时,我收到以下错误,我不知道我可以修复它。方法 Illuminate\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');
    }

【问题讨论】:

    标签: laravel laravel-8


    【解决方案1】:

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

    class Item {
        public function attachCategories($categories) {
            $this->categories()->attach($categories);
        }
    }
    

    这样可以分配这样的类别。

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

    【讨论】:

      猜你喜欢
      • 2021-06-08
      • 2021-05-30
      • 1970-01-01
      • 1970-01-01
      • 2021-03-26
      • 1970-01-01
      • 2020-03-25
      • 1970-01-01
      • 2021-08-02
      相关资源
      最近更新 更多