skip to Main Content

i’m working on a Laravel/Livewire project

there are some products and services in this platform that user can order them.

the price of these products and services are changeable by their attributes . like size,color,quality and….

and i made a Many To Many relation between products and attributes.

but a can’t handle it in my view where user should select that attributes before ordering

and my for each loop return wrong data . and i get this error :

Trying to get property ‘pivot’ of non-object .

my migration :

 public function up()
    {
        Schema::create('attr_product', function (Blueprint $table) {

            $table->foreignId('attr_id')->constrained();
            $table->foreignId('product_id')->constrained();
            $table->string('value')->nullable();
            $table->string('price')->nullable();
            $table->timestamps();
        });
    }

product model :

public function attr(){

        return $this->belongsToMany(Attr::class)->withPivot(['value','price'])->withTimestamps();
    }

attr model:

public function product(){

        return $this->belongsToMany(Product::class)->withPivot(['value','price'])->withTimestamps();
    }

my controller :

 class SingleProduct extends Component
{
    public $product;

    public function mount($id){
        $this->product=Product::with('attr')->findOrFail($id);
    }

    public function render()
    {
        return view('livewire.front.product.single-product')->extends('layouts.Default')->section('content');
    }
}

my loop in blade :

  @foreach($product->attr as $attr)
                                <div class="col-lg-4 col-sm-6 mt-3">
                                    <h6 class="mb-2 text-black">{{$attr->title}}</h6>
                                    <select class="custom-select shadow-none">
                                         @foreach($attr as $av)
                                        <option value="{{$av->pivot->price}}">{{$av->pivot->value}}</option>
                                        @endforeach
                                    </select>
                                </div>
                 


 @endforeach

2

Answers


  1. The right syntax for withPivot should be parameters separated by comma, try this:

    product model

    public function attr(){
    
            return $this->belongsToMany(Attr::class)
                   ->withPivot('value','price')
                   ->withTimestamps();
        }
    

    attr model:

    public function product(){
    
            return $this->belongsToMany(Product::class)
                   ->withPivot('value','price')
                   ->withTimestamps();
        }
    
    Login or Signup to reply.
  2. before @foreach add

    @php
    dd($product)
    @endphp
    

    You can troubleshoot your $product Model and relations

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search