Elegant collection methods, such as once or with the exception of returning an empty collection

From docs, I tested the following example using the method->only()

$collection = collect(['product_id' => 1, 'name' => 'Desk', 'price' => 100, 'discount' => false]);

$filtered = $collection->only(['product_id', 'name']);

$filtered->all();

// ['product_id' => 1, 'name' => 'Desk']

and it really works.

However , when I apply this method to the collection that I get from the database (Model),

$myCollection = MyModel::orderBy('id','desc')->paginate(5);
$filtered=$myCollection->only(['id']);
        dd(filtered);

The returned collection is empty!

Collection {#199 ▼
  #items: []
}

If I get the dd($myCollection);collection from the database, it is really filled with additions, attributes, etc. Data is displayed correctly in table view mode.

But if I apply methods ->only()or ->except()to $myCollection... the returned collection is empty.

For example, this is part of a collection where I want to show only an attribute id, or a few more, but not all:

LengthAwarePaginator {#218 ▼
  #total: 3041
  #lastPage: 609
  #items: Collection {#219 ▼
    #items: array:5 [▼
      0 => MyModel {#220 ▼
        #dates: array:1 [▶]
        #appends: array:5 [▶]
        #connection: null
        #table: null
        #primaryKey: "id"
        #keyType: "int"
        #perPage: 15
        +incrementing: true
        +timestamps: true
        #attributes: array:12 [▼
          "id" => 3041
          "date" => "2017-01-25"
          "value1" => "12"
          "value2" => "20"
          "value3" => "22"
          "value4" => "25"
          "value5" => "46"
          "value6" => "48"
          "value7" => "50"
          "value8" => "$60,000,000.00"
          "created_at" => null
          "updated_at" => null
        ]

->only(['id']), .

paginate, , , LengthAwarePaginator.

, :

    $filtered = collect(['id'=>$myCollection->pluck(['id']),'Value1'=>$myCollection->pluck('value1')]);
dd($filtered);

, , , :

Collection {#212 ▼
  #items: array:2 [▼
    "id" => Collection {#201 ▶}
    "value1" => Collection {#211 ▶}
  ]
}

? ? ?

+4
1

, only() , .

['product_id' => 1, 'name' => 'Desk', 'price' => 100, 'discount' => false]

, only() , / ( ).

[ object, object, object ]

, .

[ 'product_id' => object, 'name' => object ]

, pluck() map()

+5

Source: https://habr.com/ru/post/1668479/


All Articles