Skip to content

Commit 58a6681

Browse files
committed
added tip #344
1 parent 1fa6cb0 commit 58a6681

File tree

2 files changed

+27
-1
lines changed

2 files changed

+27
-1
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ Daily Laravel/PHP tips I share on my [X](https://x.com/OussamaMater) and [Linked
1010
Currently, there are over 300 tips categorized as follows:
1111

1212
- 🗄️ [Eloquent & Database Tips](./tips/eloquent-and-database.md) (95 tips)
13-
- 🛠️ [Helpers Tips](./tips/helpers.md) (63 tips)
13+
- 🛠️ [Helpers Tips](./tips/helpers.md) (64 tips)
1414
- 🧪 [Testing Tips](./tips/testing.md) (28 tips)
1515
- 💻 [Artisan & Console Command Tips](./tips/console.md) (26 tips)
1616
- 🔄 [Routing & Request Tips](./tips/routing.md) (22 tips)

tips/helpers.md

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1157,3 +1157,29 @@ Number::clamp(5, min: 10, max: 50); // Below the range, so the min 10 is returne
11571157

11581158
Number::clamp(20, min: 10, max: 50); // Within the range, so the original value 20 is returned
11591159
```
1160+
1161+
## Laravel Tip 💡: Select Sub-Arrays ([⬆️](#helpers-tips-cd-))
1162+
1163+
![Laravel](https://img.shields.io/badge/Laravel-%3E%3D10.45-FF2D20?style=for-the-badge&logo=laravel&logoColor=white)
1164+
1165+
There will be times when you need to extract a sub-array from the main one, whether it's from a JSON response, your models, or whatever. While you could use "map" for that, Laravel ships with a much more elegant helper, "select", just for this 🚀
1166+
1167+
```php
1168+
<?php
1169+
1170+
use App\Models\Product;
1171+
1172+
// Instead of this 🥱
1173+
Product::all()->map(
1174+
fn(Product $product) => collect($product)->only(['name', 'price'])->toArray()
1175+
);
1176+
1177+
// You can do this instead 🔥
1178+
Product::all()->select('name', 'price');
1179+
1180+
/**
1181+
* Reminders:
1182+
* - pluck() only works for a single key
1183+
* - only() can't handle nested arrays
1184+
*/
1185+
```

0 commit comments

Comments
 (0)