Koera Sam Mikorana
Koera Sam Mikorana

Reputation: 67

get data into belongsToMany relation Laravel

I am a beginner in laravel, I want to get a relation ManyToMany. This is my migration file:

public function up()
{
    Schema::create('products', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name')->unique();
        $table->string('slug')->unique();
        $table->text('description');
        $table->decimal('price', 10, 2);
        $table->string('image')->unique();
        $table->timestamps();
    });

    Schema::create('product_user', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('number')->unsigned();
        $table->integer('product_id')->unsigned()->index();
        $table->integer('user_id')->unsigned()->index();
        $table->foreign('product_id')->references('id')->on('products')->onDelete('cascade');
        $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
    });
}

and This is the product class

class Product extends Model
{
public $fillable = ['name', 'slug', 'description', 'price', 'image'];

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

in class user, i add this :

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

My problem is how to get the field number ???

@foreach($user->products as $product)
Produit : {{ $product->name }} <br/>
Slug : {{ $product->slug }}<br/>
Number : {{ /* how to get this ??? */ }}<br/>
@endforeach

Thanks

Upvotes: 3

Views: 5373

Answers (1)

Ian Rodrigues
Ian Rodrigues

Reputation: 743

You can use this:

public function products()
{
   return $this->belongsToMany('App\Models\Product')->withPivot('number');
}

and access like this:

@foreach($user->products as $product)
    Produit : {{ $product->name }} <br/>
    Slug : {{ $product->slug }}<br/>
    Number : {{ $product->pivot->number }}<br/>
@endforeach

References:

Upvotes: 3

Related Questions