A
A
Al Sm2018-03-15 12:13:00
PHP
Al Sm, 2018-03-15 12:13:00

How to improve the function?

Hello. There is a function that accepts a request, checks for new tags, if any, adds to the database, get the id and add everything to the common array with indexes, and finally synchronize.
How would you make this feature?

public static function getTags($requestTags): array
{
    $tags = [];

    if ($requestTags) {
        foreach ($requestTags as $tag) {
            if (is_numeric($tag)) {
                $tags[] = $tag;
            } else {
                $newTag = Tag::upsert(['name' => $tag]);
                $tags[] = $newTag->id;
            }
        }
    }

    return $tags;
}

Is it possible, for example, to do without the forech and use the standard functions of Php/Laravel?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
Kirill Nesmeyanov, 2018-03-15
@radio_mus

return \collect((array)$requestTags)->map(function($tag): int {
    return \is_numeric($tag) ? (int)$tag : Tag::upsert(['name' => $tag])->id;
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question