php - How to save sub attribute in 3rd table in laravel

803

I want to save mysub-attribute data in3rd table but i gotCall to undefined method App\Product::mores() error.

Logic:

Gettingproduct_id + gettingsubmore_id save it toproduct_mores table.

The issue:

The issue is that I don't want to getmore_id but instead I want to getsubmore_id.

hierarchy

  1. More = CPU
  2. Submore = Core i7
  3. Product_id = 67

Result will be like:

enter image description here

Normally i should save attribute id and that would be easy with something like this:

$product->mores()->sync($request->mores, false);

after saving product BUT as I need to gavesubmore id I get error and it says:

Call to undefined method App\Product::mores()

which lead me to:

$product->mores()->sync($request->mores, false);

Codes

create method:

public function create()
    {
      $categories = Category::all();
      $subcategories = Subcategory::all();
      $submores = Submore::all();
      $user = Auth::user();
      $brands = Brand::all();
      return view('admin.products.create', compact('user', 'categories', 'subcategories', 'submores', 'brands'));
    }

Store method:

//......
      $product->save();
      $product->mores()->sync($request->mores, false);

      //Display a successful message upon save
      Session::flash('flash_message', 'Product, '. $product->title.' created');
      return redirect()->route('products.index');

Create blade page:

  <label for="mores">Attributes</label>
  <select class="tagsselector form-control" name="mores[]" multiple="multiple">
  <option>Select Attribute</option>
    @foreach($submores as $more)
       <option value="{{ $more->id }}">{{ $more->title }}</option>
    @endforeach
  </select>

Any idea?

984

Answer

Solution:

SOLVED

All I needed was to add table and column names in my models functions like so:

public function submores()
  {
     return $this->belongsToMany(Submore::class, 'product_mores', 'product_id', 'submore_id');
  }

And also change my save function frommores tosubmores like so:

$product->submores()->sync($request->submores, false);

Then change thename andfor in my form tosubmores

<label for="submores">Attributes</label>
<select class="tagsselector form-control" name="submores[]" multiple="multiple">
//// rest of the code...

People are also looking for solutions to the problem: php - Page execution after cURL timed out

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.