Petro Gromovo
Petro Gromovo

Reputation: 2173

How to set additive parameter to laravel collection map method

In my laravel 5.7 I try to remake a small piece of application using collection

$selectedSubscriptions = [1,2,3];
$siteSubscriptionsList = [];
$siteSubscriptions     = SiteSubscription
    ::getByActive(true)
    ->orderBy('id', 'asc')
    ->get();
foreach ($siteSubscriptions as $next_key => $nextSiteSubscription) {
    $is_found = false;
    foreach ($selectedSubscriptions as $next_value) {
        if ($nextSiteSubscription->id == (int)$next_value) {
            $is_found = true;
            break;
        }
    }
    $siteSubscriptionsList[] = (object)['name' => $nextSiteSubscription->name, 'id' => $nextSiteSubscription->id, 'checked' => $is_found];
}

like :

$selectedSubscriptions = [1,2,3];
$siteSubscriptionsList     = SiteSubscription
    ::getByActive(true)
    ->orderBy('id', 'asc')
    ->get()
    ->map(function ( $item, $selectedSubscriptions ) {
        $is_found = false;
        foreach ($selectedSubscriptions as $next_value) {
            if ($item->id == (int)$next_value) {
                $is_found = true;
                break;
            }
        }
        return (object)['name' => $item->name, 'id' => $item->id, 'checked' => $is_found];

    })
    ->all();

But I need to set additive parameter $selectedSubscriptions into map function, as it does not work, as I see that inside os a map function has “0” value. How correctly?

Upvotes: 1

Views: 1243

Answers (1)

thisiskelvin
thisiskelvin

Reputation: 4202

When passing data through to the ->map() closure, you use the use statement (which follows the function() call):

$selectedSubscriptions = [1,2,3];
$siteSubscriptionsList = SiteSubscription
    ::getByActive(true)
    ->orderBy('id', 'asc')
    ->get()
    ->map(function ($item, $key) use ($selectedSubscriptions) {
        $is_found = false;
        foreach ($selectedSubscriptions as $next_value) {
            if ($item->id == (int)$next_value) {
                $is_found = true;
                break;
            }
        }
        return (object)['name' => $item->name, 'id' => $item->id, 'checked' => $is_found];

    })
    ->all();

The second parameter of ->map() will always be the variable of the $key.

Sidenote: You can reduce your foreach check for the id with the following:

$is_found = collect($selectedSubscriptions)->contains($item->id);

Upvotes: 4

Related Questions