Skip to content
Tutorials Center
My learning

Topics

Lesson 58 of 67 ยท Architecture and Extending

Packages and Extending Laravel

Use Composer packages, understand auto-discovery, add behavior with macros, write a small Laravel package with a service provider and publishable config.

Laravel is small at its core and large in practice, because of its ecosystem. Authentication scaffolding, admin panels, PDF generation, backups, payments and search are all packages you install with one Composer command. Knowing how packages plug into the framework helps you in three ways: you can choose and configure them confidently, you can extend Laravel's own classes without editing the framework, and you can package your own reusable code.

In this lesson you will learn how packages are installed and discovered, how macros add methods to framework classes, and how to write a small package with a service provider and a publishable config file. Real Laravel and Composer code is read-only here. The runnable examples are plain-PHP stand-ins for the macro system (__call and __callStatic) and for package auto-discovery.

Installing a package

Laravel uses Composer, PHP's package manager, as explained in autoloading and Composer. Installing a package is one command:

Terminal
composer require spatie/laravel-backup
composer require --dev barryvdh/laravel-debugbar

--dev marks a package that is only needed during development, so a production deploy with composer install --no-dev leaves it out. Composer records the exact version in composer.lock, which you commit. Before you add a package, check a few things: is it maintained (recent releases, open issues answered), does it support your Laravel and PHP versions, how many people use it, and is the licence compatible with your project? Every package is code that runs inside your application with full privileges, so install fewer, better ones. Run composer audit now and then to check for known vulnerabilities.

Many packages then ask you to publish their config or migrations, run php artisan migrate, or add a trait to a model. Their README is the source of truth for that part.

Package auto-discovery

You never had to write new SomePackageServiceProvider() anywhere in your app. That is package auto-discovery. A package declares its service providers (and facade aliases) in its own composer.json, under extra.laravel:

JSON
{
    "name": "acme/laravel-greeter",
    "autoload": {
        "psr-4": { "Acme\\Greeter\\": "src/" }
    },
    "extra": {
        "laravel": {
            "providers": [
                "Acme\\Greeter\\GreeterServiceProvider"
            ],
            "aliases": {
                "Greeter": "Acme\\Greeter\\Facades\\Greeter"
            }
        }
    }
}

When Composer installs or updates packages, Laravel's package:discover command (run for you from Composer scripts) reads every installed package's extra.laravel section and writes the combined list into a cache file in bootstrap/cache. At boot, Laravel registers all those providers automatically. If you ever need to stop a package from being discovered, list it under extra.laravel.dont-discover in your own composer.json.

flowchart LR
    C["composer require acme/laravel-greeter"] --> D["package:discover reads<br/>extra.laravel of every package"]
    D --> F["bootstrap/cache/packages.php"]
    F --> B["App boots: providers registered"]
    B --> R["register(): bind services"]
    R --> O["boot(): routes, views, config, commands"]

Discovery turns a Composer install into a registered service provider, with no edit in your app.

The two phases in the last boxes are the ones from service providers and facades: register() binds things in the container, and boot() runs once everything is registered.

Macros: adding methods to framework classes

A macro lets you add a method to a Laravel class at runtime, even though you do not own the class. Many core classes use the Macroable trait: Collection, Str, Arr, Request, Response, Builder, Carbon (through its own mixin support), Rule and more. You register macros in a service provider's boot() method:

PHP
use Illuminate\Support\Collection;
use Illuminate\Support\Str;

public function boot(): void
{
    Collection::macro('toUpper', function () {
        return $this->map(fn (string $value) => Str::upper($value));
    });

    Str::macro('initials', function (string $name): string {
        return collect(explode(' ', $name))
            ->map(fn (string $part) => Str::upper(Str::substr($part, 0, 1)))
            ->implode('');
    });
}

// anywhere
collect(['ada', 'grace'])->toUpper();   // ['ADA', 'GRACE']
Str::initials('Grace Hopper');          // 'GH'

Inside a macro closure on an instance method, $this refers to the object the macro was called on, so you can use the class's own methods. Macros can take arguments like any method.

For a group of related methods, use mixin(): pass an object whose public methods return closures, and each becomes a macro. That keeps a family of extensions in one class, which is easier to test:

PHP
Collection::mixin(new CollectionExtras());

How macros work

Macros are not magic. The Macroable trait stores closures in a static array and implements __call and __callStatic. When you call a method that does not exist, PHP calls __call, and the trait looks for a macro with that name and runs it with $this bound to the object (magic methods and closure binding explain the two PHP features involved). The stand-in below shows the whole mechanism in about 30 lines.

PHP A macro system built on __call and __callStatic

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Use macros sparingly. They are great for small helpers you would otherwise repeat, but they are invisible to your IDE and static analyzers unless you add stubs or use a helper such as laravel-ide-helper. If a method is complex or is used only in one place, an ordinary class is clearer.

Writing a small package

You do not have to publish a package to the world. Extracting code into a package gives you a clean boundary, and you can use a local path repository to try it in an app. A minimal package has this shape:

TEXT
acme-greeter/
  composer.json
  config/greeter.php
  src/
    Greeter.php
    GreeterServiceProvider.php
    Facades/Greeter.php
  tests/

The class that does the work knows nothing about Laravel:

PHP
namespace Acme\Greeter;

final class Greeter
{
    public function __construct(private string $greeting) {}

    public function greet(string $name): string
    {
        return "{$this->greeting}, {$name}!";
    }
}

The service provider connects it to the framework:

PHP
namespace Acme\Greeter;

use Illuminate\Support\ServiceProvider;

class GreeterServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        // defaults, so the package works without publishing anything
        $this->mergeConfigFrom(__DIR__.'/../config/greeter.php', 'greeter');

        $this->app->singleton(Greeter::class, function ($app) {
            return new Greeter($app['config']->get('greeter.greeting'));
        });
    }

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

        // $this->loadRoutesFrom(__DIR__.'/../routes/web.php');
        // $this->loadViewsFrom(__DIR__.'/../resources/views', 'greeter');
        // $this->loadMigrationsFrom(__DIR__.'/../database/migrations');
        // $this->loadTranslationsFrom(__DIR__.'/../lang', 'greeter');
    }
}

Users then run php artisan vendor:publish --tag=greeter-config to copy the config file into their config folder and change it. mergeConfigFrom() is the important companion: it merges the package defaults with the user's published file, so a setting the user did not override still has a value, and new settings added in a later package version do not break old apps.

To try the package inside an app before publishing it, point Composer at the local folder:

JSON
"repositories": [
    { "type": "path", "url": "../acme-greeter" }
],

then run composer require acme/laravel-greeter:@dev. For testing the package on its own, Orchestra Testbench boots a minimal Laravel application around your package so that you can write ordinary Pest tests against the provider, config and routes.

Package providers also add Artisan commands ($this->commands([...])), event listeners, middleware aliases and Blade components (Blade::componentNamespace(...)). Choose the loading helpers you need; a package that only adds one class needs only register().

Publishing config, as the framework does it

The mechanics of publishing and merging are simple enough to model. Package defaults, the user's published overrides and a dotted config() lookup combine as follows.

PHP Package config: defaults, publishing and overrides

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The ecosystem

You will meet these names constantly. They are first-party packages from the Laravel team unless noted:

Package What it does
Sanctum, Passport API tokens and OAuth
Fortify, starter kits Authentication backend and UIs
Cashier Subscription billing (Stripe, Paddle)
Horizon Dashboard and supervision for Redis queues
Telescope, Pulse Debugging and live application metrics
Scout Full-text search drivers
Socialite Login with Google, GitHub and others
Reverb, Echo WebSockets for real-time features
Octane Long-running application servers for speed
Livewire, Inertia Dynamic frontends without writing an API by hand
Pest, Pint Testing and code style
Spatie packages (community) Permissions, media library, backup, data objects and many more
Filament (community) Admin panels and forms

Check a package's last release and Laravel version support before relying on it, and prefer a first-party or widely used package over a brand-new one for anything security-sensitive.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. How does Laravel register a package's service provider without you editing any config?

    package:discover collects the providers declared under extra.laravel in every package and caches them, so Laravel registers them at boot.
  2. 2. What does a macro on a class that uses the Macroable trait rely on?

    When an undefined method is called, PHP invokes __call. The trait finds the macro closure by name and runs it with $this bound to the object.
  3. 3. What is mergeConfigFrom() for in a package's register() method?

    Defaults from the package are merged underneath whatever the user published, so a missing key falls back to the package default.
  4. 4. Which command copies a package's publishable config files into your app?

    vendor:publish copies the files registered with $this->publishes() to the paths in your app, usually selected with a --tag.
  5. 5. Why should you use macros sparingly?

    Macros are great for small shared helpers, but because methods are added at runtime tools cannot see them. A normal class is clearer for anything larger.

Summary

  • Install packages with composer require (--dev for development tools), choose maintained ones, and run composer audit.
  • Auto-discovery registers a package's providers and aliases from extra.laravel in its composer.json.
  • Macros add methods to classes that use Macroable, through __call and __callStatic; use mixin() for groups and use them sparingly.
  • A small package is a plain class plus a service provider that binds services, merges config with mergeConfigFrom() and offers files through publishes().
  • Orchestra Testbench lets you test a package inside a minimal Laravel app.
  • Learn the first-party ecosystem (Sanctum, Horizon, Scout, Cashier, Livewire and others) before reinventing it.

Next: Localization, Time Zones and Multi-Tenancy