Laravel Config Gets Smarter: Direct Collection Access

Laravel Config Gets Smarter: Direct Collection Access

Working with config arrays as collections in Laravel used to require the verbose collect(Config::array()) pattern. The new collection() method streamlines this into a single, clean call.

From Nested Calls to Direct Access

Previously, when you needed to use Laravel's powerful collection methods on configuration arrays, you had to combine two separate calls:

// The old verbose approach
$services = collect(Config::array('services'));
$databases = collect(Config::array('database.connections'));

The new collection() method eliminates this nesting, providing direct access to collections:

// Clean and direct
$services = Config::collection('services');
$databases = Config::collection('database.connections');

Real-World Example

Consider a multi-service application where you need to process various service configurations and database connections:

<?php

namespace App\Services;

use Illuminate\Support\Facades\Config;

class ServiceManager
{
    public function getActiveServices(): array
    {
        return Config::collection('services')
            ->filter(fn($config) => $config['enabled'] ?? false)
            ->keys()
            ->toArray();
    }

    public function getServiceUrls(): array
    {
        return Config::collection('services')
            ->pluck('url', 'name')
            ->filter()
            ->toArray();
    }

    public function validateServiceConfigs(): array
    {
        $errors = [];

        Config::collection('services')->each(function ($config, $name) use (&$errors) {
            if (empty($config['url'])) {
                $errors[] = "Service '{$name}' missing URL";
            }
            if (empty($config['api_key'])) {
                $errors[] = "Service '{$name}' missing API key";
            }
        });

        return $errors;
    }
}

class DatabaseManager 
{
    public function getReadOnlyConnections(): array
    {
        return Config::collection('database.connections')
            ->filter(fn($config) => $config['read_only'] ?? false)
            ->keys()
            ->toArray();
    }

    public function getDatabasesByDriver(): array
    {
        return Config::collection('database.connections')
            ->groupBy('driver')
            ->map(fn($group) => $group->keys())
            ->toArray();
    }
}

// Usage in controllers
class AdminController extends Controller
{
    public function servicesStatus(ServiceManager $serviceManager)
    {
        $activeServices = $serviceManager->getActiveServices();
        $serviceUrls = $serviceManager->getServiceUrls();
        $errors = $serviceManager->validateServiceConfigs();

        return view('admin.services', compact(
            'activeServices', 
            'serviceUrls', 
            'errors'
        ));
    }

    public function databaseInfo(DatabaseManager $dbManager)
    {
        return response()->json([
            'read_only_connections' => $dbManager->getReadOnlyConnections(),
            'databases_by_driver' => $dbManager->getDatabasesByDriver()
        ]);
    }
}

The collection() method is particularly useful when working with configuration files that contain arrays of structured data:

// config/features.php
return [
    'user_registration' => ['enabled' => true, 'requires_email' => true],
    'social_login' => ['enabled' => false, 'providers' => ['github', 'google']],
    'api_access' => ['enabled' => true, 'rate_limit' => 1000],
    'premium_features' => ['enabled' => true, 'trial_days' => 14],
];

// Using the collection method
class FeatureService
{
    public function getEnabledFeatures(): array
    {
        return Config::collection('features')
            ->filter(fn($config) => $config['enabled'])
            ->keys()
            ->toArray();
    }

    public function countEnabledFeatures(): int
    {
        return Config::collection('features')
            ->filter(fn($config) => $config['enabled'])
            ->count();
    }
}

This method makes configuration processing more fluent and eliminates the mental overhead of remembering to wrap config arrays with collect(). It's a small improvement that adds up to cleaner, more readable code when working with structured configuration data.


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