1

Is there a way to get all fields in the pivot table instead of to specify one by one?

For example (starting from the guide here):

shops:

  • id
  • name

products:

  • id
  • name

product_shop:

  • product_id
  • shop_id
  • field_1
  • field_2
  • field_3
  • ecc...

I do not want to specify each single field:

public function products() {
   return $this->belongsToMany('App\Product')
        ->withPivot('field_1', 'field_2', 'field_3', 'ecc..' );
}

but I would return all available fields in the table; something like ->withPivot('*');

Is there a way?

Thank you.

Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
vlauciani
  • 1,010
  • 2
  • 13
  • 27

2 Answers2

1

You could achieve this by first retrieving all the columns (fields) from the product_shop table and passing it as an array into the withPivot. See code below:

public function products() {
    $table_name = 'product_shop';

    // or you could get table name dynamically if you have a ProductShop model
    // $table_name = (new ProductShop)->getTable()

    $table_fields = Schema::getColumnListing($table_name);

    return $this->belongsToMany('App\Product')
    ->withPivot($table_fields);
}

Don't forget to import Schema:

use Illuminate\Support\Facades\Schema; 

I hope it works for you. You may want to remove some fields from the array by value. This link explains how to remove some fields.

0

There's no way to do this because it would be quite complicated.

To prevent collisions, Laravel has to add aliases for the pivot columns:

`product_shop`.`field_1` as `pivot_field_1`, ...

So Laravel would need a list of all the columns in the pivot table. The only way to get this list is a separate query to information_schema.columns.

Jonas Staudenmeir
  • 24,815
  • 6
  • 63
  • 109