Laravel Package: Service Providers &amp; Auto-Discovery | Mohamed Said       [Skip to content](#main)  [ ![](https://cdn.msaied.com/01KT78WE565VEMM3PSNQAAB0MH.png) Mohamed SaidLaravel Backend Engineer ](https://www.msaied.com/public) - [Home](https://www.msaied.com/public)
- [Projects](https://www.msaied.com/public/projects)
- [Articles](https://www.msaied.com/public/articles)
- [Certificates](https://www.msaied.com/public/certificates)
- [About](https://www.msaied.com/public#about)

           [  Contact](https://www.msaied.com/public#contact) Menu 

Menu
----

Close 

 - [HomeStart here](https://www.msaied.com/public)
- [ProjectsCase studies](https://www.msaied.com/public/projects)
- [ArticlesEngineering notes](https://www.msaied.com/public/articles)
- [CertificatesCredentials](https://www.msaied.com/public/certificates)
- [AboutHow I work](https://www.msaied.com/public#about)
- [ContactGet in touch](https://www.msaied.com/public#contact)

  [Start a conversation](https://www.msaied.com/public#contact) [WhatsApp](https://wa.me/201094619204) [Email](mailto:hello@msaied.com) 

 1. [Home](https://www.msaied.com/public)
2. /
3. [Articles](https://www.msaied.com/public/articles)
4. /
5. Laravel Package Development: Service Providers, Auto-Discovery, and Config Merging

 Laravel Package Development: Service Providers, Auto-Discovery, and Config Merging
===================================================================================

 Build a production-ready Laravel package from scratch — covering service provider design, auto-discovery via composer.json, config merging, and the pitfalls that trip up even experienced package authors.

 ![](https://cdn.msaied.com/01M22N44A70A5MC2S599JP0MPH.webp) [Mohamed Said](https://www.msaied.com/public#person) Published 15 Jun 2026 · Updated 15 Jun 2026 · 3 min read

ShareCopy linkCopied

 ![Laravel Package Development: Service Providers, Auto-Discovery, and Config Merging](https://cdn.msaied.com/195/cf77a8be5fdf1ef48927e0b210571d65.png) 

  On this page +1. [Why Package Architecture Still Trips Senior Devs](#why-package-architecture-still-trips-senior-devs)
2. [Service Provider Anatomy](#service-provider-anatomy)
3. [Auto-Discovery via composer.json](#auto-discovery-via-composerjson)
4. [Config Merging Done Right](#config-merging-done-right)
5. [Deferred Providers for Performance](#deferred-providers-for-performance)
6. [Publishable Groups and Selective Publishing](#publishable-groups-and-selective-publishing)
7. [Takeaways](#takeaways)

 Why Package Architecture Still Trips Senior Devs
------------------------------------------------

Writing a Laravel package feels straightforward until you hit subtle ordering issues, config collisions, or auto-discovery that silently fails in certain deployment pipelines. This article walks through the mechanics that matter — not the boilerplate generators, but the decisions underneath them.

---

Service Provider Anatomy
------------------------

Every package's entry point is a service provider. The two methods you'll always implement are `register` (bind things into the container) and `boot` (act on the fully-booted application).

```php
namespace Acme\Auditor;

use Illuminate\Support\ServiceProvider;

class AuditorServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        $this->mergeConfigFrom(
            __DIR__.'/../config/auditor.php',
            'auditor'
        );

        $this->app->singleton(AuditLogger::class, function ($app) {
            return new AuditLogger(
                $app['config']->get('auditor'),
                $app[\Psr\Log\LoggerInterface::class]
            );
        });
    }

    public function boot(): void
    {
        $this->publishes([
            __DIR__.'/../config/auditor.php' => config_path('auditor.php'),
        ], 'auditor-config');

        $this->loadMigrationsFrom(__DIR__.'/../database/migrations');
    }
}

```

**Key rule:** never call `config()` inside `register()`. The config repository exists, but other providers haven't merged their values yet. Read config in `boot()` or lazily inside closures.

---

Auto-Discovery via composer.json
--------------------------------

Laravel's auto-discovery reads the `extra.laravel` key so users don't need to add your provider manually.

```json
{
  "extra": {
    "laravel": {
      "providers": [
        "Acme\\Auditor\\AuditorServiceProvider"
      ],
      "aliases": {
        "Auditor": "Acme\\Auditor\\Facades\\Auditor"
      }
    }
  }
}

```

Auto-discovery runs during `composer install/update` and writes to `bootstrap/cache/packages.php`. In CI pipelines that cache the vendor directory without re-running `composer dump-autoload`, this file can be stale. Always invalidate the bootstrap cache when the vendor hash changes.

Users can opt out per-package in their own `composer.json`:

```json
{
  "extra": {
    "laravel": {
      "dont-discover": ["acme/auditor"]
    }
  }
}

```

---

Config Merging Done Right
-------------------------

`mergeConfigFrom` performs a **shallow** merge. If your config has nested arrays and the user publishes a partial override, nested keys the user omits will still come from your package defaults — but only one level deep.

```php
// Package default
return [
    'driver' => 'database',
    'channels' => ['slack', 'log'],
    'options' => ['retry' => 3, 'timeout' => 30],
];

```

If the user's published config only sets `'driver' => 'redis'`, the `options` array is preserved from your defaults. However, if they set `'options' => ['retry' => 5]`, the `timeout` key disappears — shallow merge, not recursive.

For recursive merging, do it yourself in `register()`:

```php
public function register(): void
{
    $packageConfig = require __DIR__.'/../config/auditor.php';
    $userConfig = $this->app['config']->get('auditor', []);

    $this->app['config']->set(
        'auditor',
        array_replace_recursive($packageConfig, $userConfig)
    );
}

```

---

Deferred Providers for Performance
----------------------------------

If your package only needs to resolve its bindings on demand, implement `\Illuminate\Contracts\Support\DeferrableProvider`:

```php
use Illuminate\Contracts\Support\DeferrableProvider;

class AuditorServiceProvider extends ServiceProvider implements DeferrableProvider
{
    public function provides(): array
    {
        return [AuditLogger::class];
    }
}

```

Laravel will skip booting this provider entirely until something resolves `AuditLogger::class` from the container. For packages that add CLI commands or event listeners, deferral is wrong — those need to register during every request cycle.

---

Publishable Groups and Selective Publishing
-------------------------------------------

Tag your publishable assets so users can cherry-pick:

```php
$this->publishes([
    __DIR__.'/../config/auditor.php' => config_path('auditor.php'),
], 'auditor-config');

$this->publishes([
    __DIR__.'/../resources/views' => resource_path('views/vendor/auditor'),
], 'auditor-views');

```

Users then run:

```bash
php artisan vendor:publish --tag=auditor-config

```

Avoid a catch-all publish group — it forces users to accept files they don't want to own.

---

Takeaways
---------

- Call `mergeConfigFrom` in `register()`, but read config values in `boot()` or inside lazy closures.
- Auto-discovery depends on `bootstrap/cache/packages.php` being fresh — invalidate it in CI.
- `mergeConfigFrom` is shallow; use `array_replace_recursive` when your config has meaningful nested defaults.
- Implement `DeferrableProvider` only for pure service bindings, never for providers that register listeners or commands.
- Tag publishable assets granularly so consumers publish only what they intend to maintain.

- [laravel](https://www.msaied.com/public/articles?search=laravel)
- [packages](https://www.msaied.com/public/articles?search=packages)
- [service-providers](https://www.msaied.com/public/articles?search=service-providers)
- [composer](https://www.msaied.com/public/articles?search=composer)
- [php](https://www.msaied.com/public/articles?search=php)

 Frequently asked questions 
---------------------------

  Why does my package's config not reflect user overrides when I read it inside register()?The user's config file is loaded by the ConfigServiceProvider before your package provider runs, but mergeConfigFrom merges package defaults only where the user has not set a value. If you read config inside register() before mergeConfigFrom completes, or if another provider overwrites the key later, you'll see stale values. Always read resolved config in boot() or inside a lazy closure passed to the container.

   When should I NOT use auto-discovery for my package?Skip auto-discovery (or document how to disable it) when your provider has significant boot-time cost, requires environment-specific registration, or when the package is an internal monorepo module not intended for general Composer consumption. In those cases, explicit registration in config/app.php gives the application owner full control.

   How do I test that my service provider registers bindings correctly?Use an Orchestra Testbench test case. Extend Orchestra\\Testbench\\TestCase, override getPackageProviders() to return your provider class, then assert container bindings with $this-&gt;app-&gt;bound(MyService::class) or resolve the binding and assert its type. This gives you a real Laravel application context without a full project.

   ![Mohamed Said](https://cdn.msaied.com/01M22N44A70A5MC2S599JP0MPH.webp)About the author
----------------

[Mohamed Said](https://www.msaied.com/public#person)Senior Backend Engineer specializing in Laravel, scalable SaaS platforms, APIs, and cloud infrastructure. I build secure, high-performance web applications that help businesses grow.

[About](https://www.msaied.com/public#about) [GitHub ↗](https://github.com/EG-Mohamed) [LinkedIn ↗](https://www.linkedin.com/in/msaiedm/) [WhatsApp ↗](https://wa.me/201094619204) [Email Address ↗](mailto:hello@msaied.com) [My CV ↗](https://drive.google.com/file/u/0/d/1MF20IPRJyzfy32mhEutjL5EpSls0w2Q8/view)  

   [Previous articleFrankenPHP, OPcache JIT, and Preloading: Squeezing Real Throughput from Laravel](https://www.msaied.com/public/articles/frankenphp-opcache-jit-and-preloading-squeezing-real-throughput-from-laravel) [Next articleLivewire v3 Internals: Morph Markers, JS Hooks, and Alpine Integration](https://www.msaied.com/public/articles/livewire-v3-internals-morph-markers-js-hooks-and-alpine-integration)  

   On this page
-------------

1. [Why Package Architecture Still Trips Senior Devs](#why-package-architecture-still-trips-senior-devs)
2. [Service Provider Anatomy](#service-provider-anatomy)
3. [Auto-Discovery via composer.json](#auto-discovery-via-composerjson)
4. [Config Merging Done Right](#config-merging-done-right)
5. [Deferred Providers for Performance](#deferred-providers-for-performance)
6. [Publishable Groups and Selective Publishing](#publishable-groups-and-selective-publishing)
7. [Takeaways](#takeaways)

 ###  Have a technical challenge?

 Tell me what you’re building. I reply within two working days.

[Start a conversation](https://www.msaied.com/public#contact) 

   Related articles
-----------------

 [ ![](https://cdn.msaied.com/740/cce86edc21eddcbdd2f2454fadaf9c70.png)  · 3 min read### The Pipeline Pattern in Laravel: Custom Pipelines Beyond Middleware

5 Oct 2026 ](https://www.msaied.com/public/articles/the-pipeline-pattern-in-laravel-custom-pipelines-beyond-middleware-1) [ ![](https://cdn.msaied.com/739/2d6897fdcdcf090613f96f72a64b8a78.png)  · 4 min read### MySQL Full-Text Search in Laravel: Indexes, Relevance Scoring, and Boolean Mode

4 Oct 2026 ](https://www.msaied.com/public/articles/mysql-full-text-search-in-laravel-indexes-relevance-scoring-and-boolean-mode) [ ![](https://cdn.msaied.com/738/073696a3fefe18bec825beec5ac658f5.png)  · 4 min read### Laravel Queue Rate-Limited Middleware: Throttling Jobs Without Losing Work

4 Oct 2026 ](https://www.msaied.com/public/articles/laravel-queue-rate-limited-middleware-throttling-jobs-without-losing-work) 

  Have a technical challenge?
----------------------------

Tell me what you’re building. I reply within two working days.

 [Discuss your project ↗](https://www.msaied.com/public#contact) 

  © 2026 Mohamed Said · Built with Laravel, meant to last.Senior Backend Engineer specializing in Laravel, scalable SaaS platforms, APIs, and cloud infrastructure. I build secure, high-performance web applications that help businesses grow.

 - [Home](https://www.msaied.com/public)
- [Articles](https://www.msaied.com/public/articles)
- [Certificates](https://www.msaied.com/public/certificates)
- [GitHub](https://github.com/EG-Mohamed)
- [LinkedIn](https://www.linkedin.com/in/msaiedm/)
- [WhatsApp](https://wa.me/201094619204)
- [Email Address](mailto:hello@msaied.com)
- [My CV](https://drive.google.com/file/u/0/d/1MF20IPRJyzfy32mhEutjL5EpSls0w2Q8/view)
- [Sitemap](https://www.msaied.com/public/sitemap.xml)
