Universal Array Extraction with Laravel's Arr::from() Method

Universal Array Extraction with Laravel's Arr::from() Method

Need to extract arrays from various data types? Laravel's new Arr::from() method provides a unified way to convert collections, objects, and other structures into arrays.

When working with different data types in Laravel, you often need to extract the underlying array data. The new Arr::from() method simplifies this process by handling various input types intelligently, whether they're collections, Jsonable objects, or Arrayable instances.

Let's see how it works:

use Illuminate\Support\Arr;

// From collections
Arr::from(collect(['name' => 'Laravel'])); // ['name' => 'Laravel']

// From Jsonable objects
Arr::from($jsonable); // Decodes via Jsonable interface

// From Arrayable objects
Arr::from($arrayable); // Returns via toArray() method

Real-World Example

Here's how you might use this in a data transformation service:

class DataTransformer
{
    public function normalizeInput($data)
    {
        // Convert any input to array format
        $array = Arr::from($data);
        
        return $this->processArray($array);
    }
    
    public function mergeDataSources(...$sources)
    {
        return collect($sources)
            ->map(fn($source) => Arr::from($source))
            ->reduce(fn($carry, $item) => array_merge($carry, $item), []);
    }
    
    public function validateAndTransform($input, array $rules)
    {
        $data = Arr::from($input);
        
        $validator = Validator::make($data, $rules);
        
        if ($validator->fails()) {
            throw new ValidationException($validator);
        }
        
        return $data;
    }
}

// Usage
$transformer = new DataTransformer();

$result = $transformer->normalizeInput(collect(['user' => 'John']));
$merged = $transformer->mergeDataSources(
    collect(['a' => 1]),
    new MyArrayableClass(),
    $jsonableObject
);

The Arr::from() method provides a consistent interface for array extraction, eliminating the need to check data types or call different methods based on the input structure.

Stay Updated with More Laravel Tips

Enjoyed this article? There's plenty more where that came from! Subscribe to our channels to stay updated with the latest Laravel tips, tricks, and best practices:

Subscribe to Harris Raftopoulos

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
jamie@example.com
Subscribe