Laravel Packages: Creating Your Own
You fix a bug in the Slack notification helper on one project, then remember the same class lives in three other repos, each copy slightly different. Nobody knows which one is the "real" version anymore. That's usually the point where copy-paste stops being cheaper than a package.
This post walks through building a Laravel package from an empty folder: the composer.json, a service provider, a facade, publishable config, migrations and views, an Artisan command, tests with Orchestra Testbench, and finally a release on Packagist. Along the way you'll see how Laravel wires packages in at boot, which is the same mechanism the framework uses for its own components.
My rough rule: if the same code is in three or more projects, or a feature has no business logic at all (it's purely technical plumbing), it's a package candidate. Typical candidates are API wrappers, notification channels, admin tools, and helpers.
Understanding How Laravel Packages Work
Under the hood there's nothing special here. It's an ordinary Composer package that hooks into the framework through a Service Provider. The provider registers bindings in the IoC container, registers routes, loads views, publishes configuration files, and bootstraps any other resources your package needs.
There are two kinds of packages:
- Framework-agnostic packages: plain PHP libraries with no Laravel dependency (a math utility, say). Laravel can use them, but so can any PHP project.
- Laravel-specific packages: these depend on
illuminate/supportor the full framework, and ship service providers, facades, Artisan commands, Blade components and so on.
This post is about the second type.
How a Laravel package integrates into an application
Package Directory Structure
Here's the layout I'll use for an example package called acme/notifier. It mirrors a Laravel app closely enough that anyone opening it knows where to look:
acme/notifier/
├── config/
│ └── notifier.php # Default configuration
├── database/
│ └── migrations/
│ └── create_notifications_table.php
├── resources/
│ └── views/
│ └── email.blade.php # Package views
├── routes/
│ └── web.php # Optional package routes
├── src/
│ ├── Contracts/
│ │ └── NotifierInterface.php
│ ├── Facades/
│ │ └── Notifier.php # Facade class
│ ├── Notifier.php # Main service class
│ └── NotifierServiceProvider.php
├── tests/
│ ├── Feature/
│ └── Unit/
├── .gitignore
├── composer.json
├── phpunit.xml
└── README.md
Setting Up the Package
Give the package its own Git repository and develop it locally through Composer's path repository type. That way you don't have to publish anything to Packagist while you're still changing things every five minutes.
Create the package directory
Outside your main Laravel app, create a folder for your package, e.g. ~/packages/acme/notifier.
Initialize composer.json
Run composer init inside the package directory and fill in the prompts, or write the file directly.
{
"name": "acme/notifier",
"description": "A flexible notification package for Laravel",
"type": "library",
"license": "MIT",
"authors": [
{
"name": "Your Name",
"email": "you@example.com"
}
],
"require": {
"php": "^8.1",
"illuminate/support": "^10.0|^11.0"
},
"require-dev": {
"orchestra/testbench": "^8.0|^9.0",
"phpunit/phpunit": "^10.0"
},
"autoload": {
"psr-4": {
"Acme\\Notifier\\": "src/"
}
},
"autoload-dev": {
"psr-4": {
"Acme\\Notifier\\Tests\\": "tests/"
}
},
"extra": {
"laravel": {
"providers": [
"Acme\\Notifier\\NotifierServiceProvider"
],
"aliases": {
"Notifier": "Acme\\Notifier\\Facades\\Notifier"
}
}
},
"minimum-stability": "dev",
"prefer-stable": true
}
The extra.laravel section is read by Laravel's package auto-discovery mechanism (introduced in Laravel 5.5). When someone installs your package with Composer, Laravel registers the service provider and facade for them. They don't have to touch config/app.php.
Link it to your Laravel app
In your main app's composer.json, add a path repository pointing to your local package folder, then require it.
{
"repositories": [
{
"type": "path",
"url": "../packages/acme/notifier"
}
],
"require": {
"acme/notifier": "@dev"
}
}
composer update acme/notifier
Composer will symlink the package directory into vendor/acme/notifier so changes in the package source show up in the app right away, without re-running Composer.
Two things trip people up here. First, Laravel caches discovered providers in bootstrap/cache/packages.php, so if you add or rename the provider in extra.laravel after installing, run composer dump-autoload (which triggers php artisan package:discover) before assuming your code is broken. Second, if the app has run php artisan config:cache, mergeConfigFrom() is skipped entirely and your package defaults won't appear until you run php artisan config:clear or rebuild the cache.
Writing the Service Provider
Everything in the package starts from here. Laravel calls its register() method before the application boots (bind things into the container here) and boot() after all providers are registered (use other services, register routes, views, etc.).
<?php
namespace Acme\Notifier;
use Illuminate\Support\ServiceProvider;
class NotifierServiceProvider extends ServiceProvider
{
/**
* Register bindings in the container.
* Called before boot(), so do NOT use other services here.
*/
public function register(): void
{
// Merge package config with any published version
$this->mergeConfigFrom(
__DIR__ . '/../config/notifier.php',
'notifier'
);
// Bind the main service as a singleton
$this->app->singleton(Notifier::class, function ($app) {
return new Notifier(
$app['config']->get('notifier'),
$app['log']
);
});
// Bind the interface to the implementation
$this->app->bind(
Contracts\NotifierInterface::class,
Notifier::class
);
}
/**
* Bootstrap package services.
* All providers are registered by this point.
*/
public function boot(): void
{
// Publish configuration file
$this->publishes([
__DIR__ . '/../config/notifier.php' => config_path('notifier.php'),
], 'notifier-config');
// Publish and load migrations
$this->publishes([
__DIR__ . '/../database/migrations' => database_path('migrations'),
], 'notifier-migrations');
$this->loadMigrationsFrom(__DIR__ . '/../database/migrations');
// Load package views
$this->loadViewsFrom(__DIR__ . '/../resources/views', 'notifier');
// Publish views so users can override them
$this->publishes([
__DIR__ . '/../resources/views' => resource_path('views/vendor/notifier'),
], 'notifier-views');
// Register package routes
$this->loadRoutesFrom(__DIR__ . '/../routes/web.php');
// Register Artisan commands
if ($this->app->runningInConsole()) {
$this->commands([
Console\SendNotificationCommand::class,
]);
}
}
}
register() should only bind things into the container. Don't resolve other services here, because their providers may not have run yet. boot() is called after ALL providers are registered, so it's safe to resolve other services, call Route::middleware(), or listen to events.
Creating a Facade
A facade lets users write Notifier::send($message) instead of app(Notifier::class)->send($message). The call only looks static. Each time, the facade pulls the binding out of the container, which is why you can still mock it in tests.
<?php
namespace Acme\Notifier\Facades;
use Illuminate\Support\Facades\Facade;
/**
* @method static void send(string $channel, string $message, array $options = [])
* @method static array channels()
* @method static \Acme\Notifier\Notifier channel(string $name)
*
* @see \Acme\Notifier\Notifier
*/
class Notifier extends Facade
{
protected static function getFacadeAccessor(): string
{
// Must match the key used in app->singleton() or app->bind()
return \Acme\Notifier\Notifier::class;
}
}
The @method annotations are only there for your IDE. Without them, autocompletion on Notifier:: shows nothing useful, since the facade class itself has no such methods.
The Main Service Class
<?php
namespace Acme\Notifier;
use Acme\Notifier\Contracts\NotifierInterface;
use Illuminate\Contracts\Logging\Log;
class Notifier implements NotifierInterface
{
protected array $config;
protected Log $logger;
protected array $resolvedChannels = [];
public function __construct(array $config, Log $logger)
{
$this->config = $config;
$this->logger = $logger;
}
public function send(string $channel, string $message, array $options = []): void
{
$driver = $this->channel($channel);
$driver->deliver($message, array_merge($this->config['defaults'] ?? [], $options));
$this->logger->info("Notifier: sent via {$channel}", ['message' => $message]);
}
public function channel(string $name): ChannelDriver
{
if (!isset($this->resolvedChannels[$name])) {
$driverClass = $this->config['channels'][$name]['driver']
?? throw new \InvalidArgumentException("Channel [{$name}] not configured.");
$this->resolvedChannels[$name] = new $driverClass(
$this->config['channels'][$name]
);
}
return $this->resolvedChannels[$name];
}
public function channels(): array
{
return array_keys($this->config['channels'] ?? []);
}
}
Configuration, Migrations & Views
Publishing lets users change your defaults without editing anything in vendor/. Two methods work together here: publishes() copies files on demand, and mergeConfigFrom() ensures your defaults always apply even if the user never publishes.
Place defaults in config/notifier.php:
<?php
return [
/*
* Default channel used when none is specified.
*/
'default' => env('NOTIFIER_CHANNEL', 'slack'),
/*
* Default options merged into every send() call.
*/
'defaults' => [
'timeout' => 5,
'retry' => 2,
],
/*
* Channel driver configurations.
*/
'channels' => [
'slack' => [
'driver' => \Acme\Notifier\Drivers\SlackDriver::class,
'webhook' => env('SLACK_WEBHOOK_URL'),
],
'discord' => [
'driver' => \Acme\Notifier\Drivers\DiscordDriver::class,
'webhook' => env('DISCORD_WEBHOOK_URL'),
],
],
];
// Users publish this file and override values:
// php artisan vendor:publish --tag=notifier-config
Migrations live in database/migrations/. Use a timestamp-based name so they don't collide with app migrations:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('notifier_logs', function (Blueprint $table) {
$table->id();
$table->string('channel');
$table->text('message');
$table->json('options')->nullable();
$table->string('status')->default('sent');
$table->timestamps();
});
}
public function down(): void
{
Schema::dropIfExists('notifier_logs');
}
};
// Load without publishing (runs automatically):
// $this->loadMigrationsFrom(__DIR__ . '/../database/migrations');
// Publish to let users inspect/edit:
// php artisan vendor:publish --tag=notifier-migrations
Views use a namespace so they don't clash with the app's view files:
{{-- resources/views/email.blade.php --}}
<!DOCTYPE html>
<html>
<body>
<h1>{{ $subject }}</h1>
<p>{{ $message }}</p>
<p>Sent via Notifier by <a href="{{ $senderUrl }}">{{ $senderName }}</a></p>
</body>
</html>
<!-- Referenced with the package namespace: notifier:: -->
<?php
// In PHP code:
return view('notifier::email', [
'subject' => 'Hello',
'message' => 'This is a test.',
'senderName' => config('app.name'),
'senderUrl' => config('app.url'),
]);
// Users can override by publishing:
// php artisan vendor:publish --tag=notifier-views
// Then edit: resources/views/vendor/notifier/email.blade.php
Route files are loaded with loadRoutesFrom(). Prefix them to avoid conflicts:
<?php
// routes/web.php
use Illuminate\Support\Facades\Route;
use Acme\Notifier\Http\Controllers\WebhookController;
Route::prefix('notifier')
->middleware(['web'])
->name('notifier.')
->group(function () {
// Receive incoming webhook callbacks
Route::post('/webhook/{channel}', WebhookController::class)
->name('webhook');
// Status dashboard (guarded by auth middleware)
Route::get('/dashboard', function () {
return view('notifier::dashboard');
})->middleware('auth')->name('dashboard');
});
Adding Artisan Commands
Package commands get registered in the service provider's boot() method inside an if ($this->app->runningInConsole()) guard so they don't load during every web request.
<?php
namespace Acme\Notifier\Console;
use Acme\Notifier\Facades\Notifier;
use Illuminate\Console\Command;
class SendNotificationCommand extends Command
{
protected $signature = 'notifier:send
{message : The message to send}
{--channel= : Override the default channel}';
protected $description = 'Send a notification via the configured channel';
public function handle(): int
{
$channel = $this->option('channel') ?? config('notifier.default');
$message = $this->argument('message');
$this->info("Sending to [{$channel}]...");
try {
Notifier::send($channel, $message);
$this->info('Notification sent successfully.');
} catch (\Exception $e) {
$this->error('Failed: ' . $e->getMessage());
return Command::FAILURE;
}
return Command::SUCCESS;
}
}
// Usage:
// php artisan notifier:send "Deploy complete" --channel=discord
Testing Your Package
A package has no app around it, so there's nothing to boot your provider in a test. Orchestra Testbench fills that gap: it spins up a small Laravel app that you configure from inside your test case.
Install Orchestra Testbench
Add it to require-dev in your package's composer.json, then run composer install inside the package folder.
<?php
namespace Acme\Notifier\Tests;
use Acme\Notifier\NotifierServiceProvider;
use Orchestra\Testbench\TestCase as OrchestraTestCase;
abstract class TestCase extends OrchestraTestCase
{
/**
* Register the package service provider(s) for the test app.
*/
protected function getPackageProviders($app): array
{
return [
NotifierServiceProvider::class,
];
}
/**
* Register facade aliases.
*/
protected function getPackageAliases($app): array
{
return [
'Notifier' => \Acme\Notifier\Facades\Notifier::class,
];
}
/**
* Seed the test app configuration.
*/
protected function defineEnvironment($app): void
{
$app['config']->set('notifier.default', 'fake');
$app['config']->set('notifier.channels.fake', [
'driver' => \Acme\Notifier\Tests\Fakes\FakeDriver::class,
]);
}
}
<?php
namespace Acme\Notifier\Tests\Feature;
use Acme\Notifier\Facades\Notifier;
use Acme\Notifier\Tests\TestCase;
class NotifierTest extends TestCase
{
/** @test */
public function it_resolves_from_the_container(): void
{
$notifier = $this->app->make(\Acme\Notifier\Notifier::class);
$this->assertInstanceOf(\Acme\Notifier\Notifier::class, $notifier);
}
/** @test */
public function it_sends_via_the_default_channel(): void
{
// Act
Notifier::send('fake', 'Hello from tests');
// Assert: the FakeDriver records all messages
$messages = Notifier::channel('fake')->sent();
$this->assertCount(1, $messages);
$this->assertSame('Hello from tests', $messages[0]);
}
/** @test */
public function it_throws_for_unconfigured_channel(): void
{
$this->expectException(\InvalidArgumentException::class);
Notifier::send('nonexistent', 'Will fail');
}
/** @test */
public function it_lists_available_channels(): void
{
$channels = Notifier::channels();
$this->assertContains('fake', $channels);
}
}
// Run tests from the package directory:
// ./vendor/bin/phpunit
In an app, clicking around usually catches a regression. In a package, the bug often only shows up in someone else's app with a config you never tried. Tests are the only thing standing between your next release and their broken deploy.
Publishing to Packagist
Once the package is tested, you can make it installable for anyone through Packagist, the default Composer repository. (For private code, skip this and point Composer at a private Git repo or Private Packagist instead.)
Push to GitHub
Create a public GitHub repository and push your package. Make sure composer.json is at the root and your autoload namespaces are correct.
Register on Packagist
Log in to packagist.org, click "Submit", paste your GitHub URL, and click "Check". Packagist will validate your composer.json.
Tag a stable release
Packagist tracks your Git tags. Create a semantic version tag (v1.0.0) and Packagist will index it as a stable release within minutes.
# Create and push a version tag
git tag v1.0.0
git push origin v1.0.0
# Users can now require the package:
# composer require acme/notifier
# Or specify a version constraint:
# composer require acme/notifier:"^1.0"
Set up a GitHub webhook
In your Packagist profile, copy your API token. In GitHub, add a webhook pointing to https://packagist.org/api/github?username=YOUR_USERNAME with your token so Packagist auto-updates on every push.
Package Development Best Practices
| Practice | Why It Matters |
|---|---|
| Use interfaces for the core service | Users can swap implementations; tests can mock easily |
| Tag publishes with specific group names | Users can publish only what they need (--tag=notifier-config) |
Guard commands with runningInConsole() |
Avoids loading heavy CLI dependencies on web requests |
Use mergeConfigFrom() in register() |
Defaults always work even if users never publish the config |
Require only illuminate/support, not laravel/framework |
Keeps the package installable in Lumen and non-standard setups |
| Keep a CHANGELOG.md | Users know what changed between versions before upgrading |
| Set up GitHub Actions CI | Run tests against multiple PHP and Laravel versions on every PR |
Artisan vendor:publish Tags Cheatsheet
| Command | What it does |
|---|---|
php artisan vendor:publish --tag=notifier-config | Copies config/notifier.php to the app's config dir |
php artisan vendor:publish --tag=notifier-migrations | Copies migrations so users can customise them |
php artisan vendor:publish --tag=notifier-views | Copies views to resources/views/vendor/notifier/ |
php artisan vendor:publish --provider="Acme\Notifier\NotifierServiceProvider" | Publishes everything registered by this provider |
php artisan vendor:publish --force | Overwrites already-published files |
Iterative package development: write, test, integrate, release
When I'd extract a package (and when I wouldn't)
A package pays off when the code is stable, has no business rules baked in, and is used in several places. API clients, notification channels, and small admin tools fit well. You fix a bug once, tag a release, and every project picks it up with composer update.
It's the wrong move when the code is still changing every week, or when it's really part of one app's domain. Each change now means editing the package, tagging a version, and bumping it in every consumer. For code shared only inside one codebase, a plain class in app/Support or a local path repository in a monorepo is usually less work.
Mistakes I see most often
- Resolving services in
register(): works on your machine, then breaks when provider order changes in someone else's app. - Requiring
laravel/frameworkinstead of the specificilluminate/*components, which makes version conflicts much more likely. - Over-wide version constraints like
"*"for Laravel. Only claim support for versions your CI actually tests. - Breaking changes in a minor release: renaming a config key in 1.3.0 breaks every app that published the old config. Save it for 2.0 and note it in the CHANGELOG.
If you're unsure, start with the path repository setup from earlier. You get a clean boundary and real tests without committing to a public release, and pushing to Packagist later is just a tag away.