Search code examples
phplaravel-5many-to-many

laravel call to a member function categories() on integer


I am trying to update and existing record in pivot table for many to many relationsip with laravel.

I have store function that work :

public function store(Request $request)
{
    $produk = new product($request->input()) ;

    $feat = (boolean)$request->input('featured');
    $input = $request->all();
    $input['featured'] = $feat;

    $inputproduk = product::create($input);
    $inputproduk->categories()->attach($request->input('kat_id'));
    return redirect()->back()->with('message', 'Memasukkan Data Produk Berhasil');
}

But why my update function didn't work???

public function update(Request $request, $id)
{
    $produk = Product::FindorFail($id);

    $produk = new product($request->input()) ;

    $input = $request->except('_method', '_token', 'picture', 'kat_id');
    $inputproduk = product::whereId($id)->update($input);
    $inputproduk->categories()->sync($request->input('kat_id'));

    return redirect()->back()->with('message', 'Mengedit Data Produk Berhasil');

}

The error is :

Call to a member function categories() on integer

What is that mean? Please help me.

View :

        <div class="form-group">
          <label for="KategoriProduk">Kategori Produk</label>
          <select class="form-control" name="kat_id[]" multiple>
            @foreach($kategoris as $value)
              <option value="{{$value->id}}">{{$value->namekat}}</option>
            @endforeach
          </select>
        </div>

I only post partially because if I post it all then the question is just full of code. Tell me if you need more.


Solution

  • It's because of the following line.

    $inputproduk = product::whereId($id)->update($input);
    

    When you call update it will return an integer not a product object.

    What you can do is first get the product and then update.

    $inputproduk = product::whereId($id)->first();
    $inputproduk->update($input);
    $inputproduk->categories()->sync($request->input('kat_id'));