Using Laravel's Collection::wrap to Convert Any Value into a Collection
The article explains Laravel's Collection::wrap method, showing basic usage for wrapping scalars, arrays, or existing collections, and provides real-world examples within a data‑processing service to streamline handling of items, tags, and search results.
Laravel provides the Collection::wrap method, which can effortlessly convert any value—whether a scalar, array, or object—into a collection, ensuring consistent collection handling throughout your code.
Basic Usage
Wrap different types of values into a collection:
use Illuminate\Support\Collection;
// Wrap a single value
$collection = Collection::wrap('John Doe');
// Result: ['John Doe']
// Wrap an array
$collection = Collection::wrap(['John Doe']);
// Result: ['John Doe']
// Wrap an existing collection
$collection = Collection::wrap(collect('John Doe'));
// Result: ['John Doe']Real‑World Example
Below is a typical usage within a data‑processing service:
class DataProcessor
{
public function processItems($items)
{
return Collection::wrap($items)
->map(fn($item) => $this->formatItem($item))
->filter()
->values();
}
public function addTags($entity, $tags)
{
$existingTags = $entity->tags;
$newTags = Collection::wrap($tags)
->unique()
->diff($existingTags);
$entity->tags()->attach($newTags);
return $entity;
}
public function processSearchResults($results)
{
return Collection::wrap($results)
->map(fn($result) => [
'id' => $result->id,
'title' => $result->title,
'url' => $result->url,
])
->sortBy('title');
}
}
// Usage in a controller
class SearchController extends Controller
{
public function search(Request $request, DataProcessor $processor)
{
$results = SearchService::find($request->query);
return $processor->processSearchResults($results);
}
}The wrap method unifies various input types into a collection, improving code reliability, flexibility, and simplifying subsequent collection operations.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.