Extend Arr
support adding a destructure
method to have a powerful array destruction in Laravel.
The package supports Laravel 8.x
and PHP >= 7.4
.
You can install the package via composer:
composer require danilopolani/laravel-array-destructuring
Thanks to the package auto-discovery feature, it will register itself automatically.
Note: if a key is not found its value will be
null
. If all the elements inside a group of keys are not found, the returned value will be an empty array[]
.
Basic destructuring for a key only
$post = [
'title' => 'Article 1',
'slug' => 'article-1',
'description' => 'Lorem ipsum',
'tags' => ['foo', 'bar'],
'gallery' => [
['image' => 'image.jpg'],
['image' => 'image2.jpg'],
],
];
[$tags, $article] = Arr::destructure($post, 'tags');
dump($tags); // ['foo', 'bar']
dump($article) // ['title' => 'Article 1', 'slug' => 'article-1', ...] without tags
[$notFoundKey, $article] = Arr::destructure($post, 'notFoundKey');
dump($notFoundKey); // null
Destructuring with multiple keys
$post = [
'title' => 'Article 1',
'slug' => 'article-1',
'description' => 'Lorem ipsum',
'tags' => ['foo', 'bar'],
'gallery' => [
['image' => 'image.jpg'],
['image' => 'image2.jpg'],
],
];
[$tags, $gallery, $article] = Arr::destructure($post, ['tags', 'gallery']);
dump($tags); // ['foo', 'bar']
dump($gallery); // [['image' => 'image.jpg'], ['image' => 'image2.jpg']]
dump($article) // ['title' => 'Article 1', 'slug' => 'article-1', 'description' => 'Lorem ipsum']
Destructuring with multiple grouped keys
$post = [
'title' => 'Article 1',
'slug' => 'article-1',
'description' => 'Lorem ipsum',
'tags' => ['foo', 'bar'],
'gallery' => [
['image' => 'image.jpg'],
['image' => 'image2.jpg'],
],
];
[$slug, $meta, $article] = Arr::destructure($post, ['slug', ['tags', 'gallery']]);
dump($slug); // article-1
dump($meta); // ['tags' => ['foo', 'bar'], 'gallery' => ['image' => 'image.jpg'], ['image' => 'image2.jpg']]
dump($article) // ['title' => 'Article 1', 'description' => 'Lorem ipsum']
[$notFoundGroup, $article] = Arr::destructure($post, [['notFound1', 'notFound2']]);
dump($notFoundGroup); // []
Please see CHANGELOG for more information what has changed recently.
Please see CONTRIBUTING for details.
Clone the repository and just run
composer test
With Docker (Windows):
docker run --rm -v %cd%:/app composer:latest bash -c "cd /app && composer install --ignore-platform-reqs && ./vendor/bin/phpunit"
With Docker (Linux/OSX):
docker run --rm -v $(pwd):/app composer:latest bash -c "cd /app && composer install && ./vendor/bin/phpunit"
If you discover any security related issues, please email danilo.polani@gmail.com instead of using the issue tracker.
The MIT License (MIT). Please see License File for more information.
This package was generated using the Laravel Package Boilerplate.