Skip to content

Instantly share code, notes, and snippets.

@a2sc
Last active November 21, 2019 04:08
Show Gist options
  • Save a2sc/eb810e389898c34575527ddba291b0ad to your computer and use it in GitHub Desktop.
Save a2sc/eb810e389898c34575527ddba291b0ad to your computer and use it in GitHub Desktop.
Laravel Collection tips

Laravel Collection tips

Pluck method

Using dot notation and wildcard:

Example #1

$posts = collect([
    [
        'title' => 'Learn Laravel',
        'tags' => [
            ['name' => 'Laravel'],
            ['name' => 'PHP']
        ],
    ],
    [
        'title' => 'Testing Your Laravel Application',
        'tags' => [
            ['name' => 'Laravel'],
            ['name' => 'PHP'],
            ['name' => 'Testing']
        ],
    ],
    [
        'title' => 'Testing Vue',
        'tags' => [
            ['name' => 'Vue'],
            ['name' => 'JavaScript'],
            ['name' => 'Testing']
        ],
    ],
]);
$posts->pluck('tags.*.name')->all();

// [
//     ["Laravel", "PHP"],
//     ["Laravel", "PHP", "Testing"],
//     ["Vue", "JavaScript", "Testing"],
// ]

Example #2

$posts = collect([
    [
        'title' => 'Learn Laravel',
        'tags' => [['Laravel'], ['PHP']],
    ],
    [
        'title' => 'Testing Your Laravel Application',
        'tags' => [['Laravel'], ['PHP'], ['Testing']],
    ],
    [
        'title' => 'Testing Vue',
        'tags' => [ ['Vue'], ['JavaScript'], ['Testing']],
    ]
]);
$posts->pluck('tags.*.*')->all();

// [
//     ["Laravel", "PHP"],
//     ["Laravel", "PHP", "Testing"],
//     ["Vue", "JavaScript", "Testing"],
// ]

Example #3

$posts = collect([
    [
        'title' => 'Learn Laravel',
        'tags' => [
            ['name' => 'Laravel'],
            ['name' => 'PHP']
        ],
    ],
    [
        'title' => 'Testing Your Laravel Application',
        'tags' => [
            ['name' => 'Laravel'],
            ['name' => 'PHP'],
            ['name' => 'Testing']
        ],
    ],
    [
        'title' => 'Testing Vue',
        'tags' => [
            ['name' => 'Vue'],
            ['name' => 'JavaScript'],
            ['name' => 'Testing']
        ],
    ],
]);
$posts->pluck('tags.*.name')->collapse()->unique()->all();

// ['Laravel', 'PHP', 'Testing', 'Vue', 'JavaScript']
$posts->pluck('tags.*.*')->collapse()->unique()->all();

// ['Laravel', 'PHP', 'Testing', 'Vue', 'JavaScript']
$posts->pluck('tags.*.name', 'title')->all();

// [
//   "Learn Laravel" => ["Laravel", "PHP"],
//   "Testing Your Laravel Application" => ["Laravel", "PHP", "Testing"],
//   "Testing Vue" => ["Vue", "JavaScript", "Testing"],
// ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment