Contents
Introduction
Types of packages
Characteristics of a package
The Laravel package!
Components of a Laravel package
Example of a Laravel package
Creating your Laravel package
1- Package structure
2- Required equipments
3- Create package structure
4- Update package manifest
5- Create route
6- Create configuration file
7- Create command for package
8- Create controller
9- Create middleware
10- Create [database] migration
11- Create view
12- Create [view] assets
13- Create service provider
14- Create a manual/help file
15- Build our package
16- Test/Use our package
Best practices
Publish your Laravel package
Conclusion
Introduction
In context of software development - particularly with PHP - a package is a modular, reusable piece of functionality that can be integrated into an application. Packages are designed to extend or enhance capabilities of a application by adding specific features or tools without reinventing wheel!
Now why use packages instead of developing built-in code and features?
Because:
- Save time & effort: Instead of coding complex functionality (like payments, authn, or APIs), you use a well-tested package, by too many users (well-cooked)
- Follow best practices: Good packages are built by experts(mostly), ensuring security, performance, and maintainability.
- Easy updates: When a package improves, you get upgrades without rewriting your code.
(composer update vendorname/packagename)
- Community-Powered: Many packages are open-source, meaning developers worldwide contribute to improve them.
So let's avoid reinventing wheel!
Types of packages
Each type of package solves problems at different levels - from tiny utilities, authn, dev tools to massive libraries - all shareable through dependency manager(like Composer) and designed to work harmoniously in your project ecosystem. These types are:
Standalone packages: AKA framework-agnostic packages, these are general-purpose packages that can be used with/without any PHP framework. Like guzzlehttp, monolog, redbean, etc...
Framework-Specific packages: These are tailored specifically for framework(Laravel, Symfony, YAF...) and leverage its features, such as service providers, facades, and configuration systems. Like spatie/laravel-permission, wordpress plugins, symfony/console, codeigniter4/cache, etc...
Characteristics of a package
A package is defined by following key characteristics:
Reusability: A package encapsulates functionality that can be reused across multiple applications.
Modularity: It is self-contained, meaning it includes all necessary components (like routes, controllers, views, configuration files) to perform its intended function.
Dependency management: Application's packages often rely on Composer, PHP's dependency manager, for installation and version control.
These traits ensure that packages maintain consistency, reduce redundancy, and simplify integration in software development.
The Laravel package!
A Laravel package is like a ready-made toolbox that adds extra features to our Laravel application. This can be a kind of Open-Close principle... Instead of building everything from scratch, you can install a package to quickly add things like:
Authentication (signin/signup/signout)
Payment processing (Stripe, PayPal)
File uploads
API tools
Admin dashboards
etc...
Packages save you time and let you focus on our application's unique parts. They’re easy to install (usually via Composer) and often come with clear instructions(I hope :D).
Think of them as "plugins" for Laravel!
Components of a Laravel package
A Laravel package is made up of several key components that work together to extend our application's functionality. It bundles some components to provide reusable functionality. Once structured correctly, users/developers can install it via Composer and integrate it seamlessly into their applications...
Here is components of a Laravel package:
Service Provider: "bridge" between our package and Laravel. Registers our package’s services, routes, views, and configurations.
Configuration file: A config file (usually config/mypackagename.php) where users/developers can customize package settings.
Routes: Defines web or API routes for our package.
Migrations: Database tables and required records/rows needed by our package. (if our package needs data storage)
Views: Frontend components (HTML mostly) stored in resources/views/.
Controllers: Handles logic and processes requests. Like a microcontroller in electronic world!
Models: Interacts with database. Mirror of a table in database. (if our package needs data storage)
Assets: Frontend assets (JavaScript, CSS, images) stored in resources/assets/.
Commands: Custom Artisan commands for package-specific tasks. Like
php artisan mypackagename:install
Facades: Provides a simple interface to our package features. Like
MyPackageName::doSomething()
Middleware: Adds request/response filtering for our package. Like authn checks.
Tests: PHPUnit or Pest tests to ensure reliability and QA.
Composer.json: Defines package dependencies, autoloading, and metadata... (something like manifest)
Note that some of components are optional and can be ignored in packages.
Example of a Laravel package
Now here's a great example of a popular Laravel package to quick-start: Laravel Horizon
It provides a beautiful UI for managing our Redis queues... What it does, gives us a cool dashboard and powerful tools to monitor and manage our Laravel queues. It's like having mission control for our background jobs.
Installation
composer require laravel/horizon
Configuration
php artisan horizon:install
Usage
Access the dashboard at http://domain/horizon (behind authn by default)
See? too easy!
This Laravel package is perfect for apps that handle email processing, report generation, or any heavy background tasks...
Creating your Laravel package
Laravel packages let you encapsulate reusable functionality - whether it's a handy utility, a full-featured module, or an integration with an external service. By creating your own package, you can share code across projects, maintain clean architecture by separating concerns, contribute to open-source and boost your dev cred!
To create your own Laravel package, you should simply: setup the package structure, define a service provider, publish assets, test the package, and finally distribute via Packagist. That's all
Let's start!
1- Package structure
The structure of our package will be something like this:
All components were explained in section "Components of a Laravel package" above.
my-package/
├── src/
│ ├── MyPackageServiceProvider.php
| ├── Http/
│ │ ├── Middleware/
│ │ │ └── ExampleMiddleware.php
│ │ └── Controllers/
│ │ └── ExampleController.php
│ ├── Console/
│ │ └── Commands/
│ │ └── ExampleCommand.php
│ ├── migrations/
│ │ └── 2023_12_05_000000_create_examples_table.php
│ ├── resources/
│ │ ├── views/
│ │ │ └── example.blade.php
│ │ └── assets/
│ │ └── css/
│ │ └── example.css
│ ├── config/
│ │ └── my-package.php
│ └── routes/
│ └── web.php
├── composer.json
└── README.md
And yes, we are keeping config, database, routes, and resources directories INSIDE src directory. Because this style is a self-contained structure, simpler publishing, and fits small projects.
But keeping config, database, routes, and resources directories OUTSIDE src directory fits large or public packages, aligns with Laravel community standards, and ensures PSR-4 compliance.
Note: Both styles are valid, but decision depends on your package's purpose and audience... For most developers, especially those contributing to Laravel ecosystem, outside src structure is preferred because it adheres to widely accepted conventions and improves maintainability. However, for internal or smaller projects, inside src structure can offer simplicity and encapsulation.
2- Required equipments
1- Infrastructure: PC! (laptop or desktop)
2- Platform: Windows or GNU/Linux OS
3- Interpreter: PHP >= 7.4
4- Dependency manager: Composer
5- Editor/IDE: Apache Netbeans, Ms VSCode, Eclipse IDE, Notepad++, Vim, etc...
6- Web server: Apache HTTPD, NGINX, PHP's built-in server
3- Create package structure
Now create all directories and files(empty) like above... To do this, you can use composer init
and answer questions to bootstrap our package.
Or open system terminal/CMD and use mkdir dirname
, touch filename
, echo > filename
commands to create them manually.
Or download & run my shell scripts to generate them for you: Windows BATCH, GNU/Linux BASh
4- Update package manifest
Now we must update our composer.json file for package needs:
{
"name": "example/my-package",
"description": "A simple Laravel package for example.",
"type": "library",
"version": "1.0.0",
"authors": [
{
"name": "Your Fullname",
"email": "[email protected]"
}
],
"require": {
"php": "7.4.*",
"illuminate/support": "10.*",
"illuminate/console": "10.*",
"illuminate/database": "10.*",
"illuminate/routing": "10.*"
},
"autoload": {
"psr-4": {
"Example\\MyPackage\\": "src/"
}
},
"extra": {
"laravel": {
"providers": [
"Example\\MyPackage\\MyPackageServiceProvider"
]
}
}
}
Some explanation:
"version"
tag will be match with your Git's repository tag."psr-4"
tag defines how PHP classes are designed and autoloaded. Look for classes by PSR-4 STYLE in that folder when I use this namespace."Example\\MyPackage\\"
tag is our logical(inside codes) path which maps to our "src/" physical(filesystem) path."laravel": {"providers".
.. tags are for Laravel-specific packages (uses Laravel features). And it's auto-registers our ServiceProvider when someone installs our package via Composer.
Note: When creating a Laravel package, you do NOT need to require the entire laravel/framework in your manifest file composer.json. Instead, you should only require the specific components("illuminate" packages) that your package depends on. By this way your package remains lightweight and does not include unnecessary of dependencies on the projects that use it. (avoid dependency hell!)
5- Create route
File src/routes/web.php:
<?php
use Illuminate\Support\Facades\Route;
use Example\MyPackage\Http\Controllers\ExampleController;
Route::get('/example', [ExampleController::class, 'index'])
->middleware('example.middleware') // Apply our middleware directly. Type: Route Middleware
->name('example.index'); // Assign a name to the route.
Some explanation:
'/example'
our package's feature URL.
'index'
our ExampleController's method to call.
->name('example.index')
a unique name for that route/URL. So we can call it anywhere instead of hardcoding it's URL. Can be used in:
// Blade template
<a href="{{ route('example.index') }}">Example</a>
// Controller
return redirect()->route('example.index');
// Middleware or services
$url = route('example.index');
// Testing (PHPUnit)
$response = $this->get(route('example.index'));
6- Create configuration file
File src/config/my-package.php:
<?php
return [
'greeting' => 'Awesome hello from MyPackage!!',
];
A complex config!
7- Create command for package
This command can be used by user/developer in their Laravel application.
File src\Console\Commands\ExampleCommand.php:
<?php
namespace Example\MyPackage\Console\Commands;
use Illuminate\Console\Command;
class ExampleCommand extends Command
{
protected $signature = 'my-package:example'; // The command that user uses and run.
protected $description = 'An example command description for MyPackage.';
public function handle()
{
// Example logic.
$this->info('Hello from MyPackage command!');
}
}
Example usage in Laravel application: php artisan my-package:example
8- Create controller
File src/Http/Controllers/ExampleController.php:
<?php
namespace Example\MyPackage\Http\Controllers;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\Config;
class ExampleController extends Controller
{
public function index()
{
$greeting = config('my-package.greeting');
return view('my-package::example', compact('greeting'));
}
}
The double colon (::) in view('my-package::example')
is Laravel's syntax for package views, and it prevents naming collisions.
Because imagine our package has example.blade.php file, and the main app(consumer) also has example.blade.php file...! so that namespace ensures Laravel uses the correct file.
my-package = Our package's view namespace (registered via
loadViewsFrom()
)example = The view file name (without .blade.php)Because using the namespace (::) prevents naming collisions.
Note: For better organization, always put all HTTP protocol related classes (Controllers) under /Http/ directory.
9- Create middleware
A middleware is a gatekeeper for HTTP requests in our package. It checks, modifies, or blocks requests before they reach our routes/controllers.
There are 3 types of middlewares:
Global = Runs on every HTTP request, like CORS headers, applies in Kernel.php file.
Route = Runs on specific routes, like Authentication & role checks, applies in routes files.
Group = Runs on routes in a named group, like API auth & web session handling, applies in routes files.
File src/Http/Middleware/ExampleMiddleware.php:
<?php
namespace Example\MyPackage\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Response;
class ExampleMiddleware
{
public function handle($request, Closure $next)
{
// Example logic.
if ($request->has('allow')) {
return $next($request);
}
return response('Access Denied! XD', 403);
}
}
Then register the middleware in the our package's service provider, inside boot()
method.
File src/MyPackageServiceProvider.php:
class MyPackageServiceProvider extends ServiceProvider
{
public function boot()
{
// Register our package's middleware.
$this->app['router']->aliasMiddleware('example.middleware', ExampleMiddleware::class);
In Laravel, middlewares are typically registered in boot()
method of a service provider rather than register()
method... because:
register()
method is primarily used for binding services into container. Since middlewares DO NOT need to be bound into the service container, this method isn't suitable for middleware registration.boot()
method is where middleware should be registered, because it gets executed AFTER all services have been registered. So middlewares consumes those services!
Another thing, it doesn't technically matter if you put middleware at top or bottom of boot()
method, but there's best practices to put middleware at the TOP of boot()
if:
It's essential for other package features (routes, controllers, etc.)
It's a global middleware (runs on every request)
Note: For better organization, always put all HTTP protocol related classes (Middleware) under /Http/ directory.
10- Create [database] migration
File src/migrations/2023_12_05_000000_create_examples_table.php:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateExamplesTable extends Migration
{
public function up()
{
Schema::create('examples', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('examples');
}
}
Note that Laravel will automatically include our package's migrations...
Blueprint, really nice class name.
11- Create view
File src/resources/views/example.blade.php:
<!DOCTYPE html>
<html>
<head>
<title>MyPackage</title>
<link rel="stylesheet" href="{{ asset('vendor/my-package/css/example.css') }}">
</head>
<body>
<h1>{{ $greeting }}</h1>
</body>
</html>
This asset/CSS will resolve to http://<domain>/vendor/my-package/css/example.css
URL.
12- Create [view] assets
File src/resources/assets/css/example.css:
body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
text-align: center;
padding: 50px;
}
h1 {
color: #268f22;
}
13- Create service provider (the bridge)
The service provider is the entry point of package. It registers routes, middleware, commands, and other components...
File src/MyPackageServiceProvider.php:
<?php
namespace Example\MyPackage;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\URL;
use Example\MyPackage\Console\Commands\ExampleCommand;
use Example\MyPackage\Http\Middleware\ExampleMiddleware;
class MyPackageServiceProvider extends ServiceProvider
{
public function boot()
{
// Register our middleware.
$this->app['router']->aliasMiddleware('example.middleware', ExampleMiddleware::class);
// Publish configuration file.
$this->publishes([
__DIR__ . '/config/my-package.php' => config_path('my-package.php'),
], 'config');
// Register migrations.
$this->loadMigrationsFrom(__DIR__ . '/migrations');
// Register routes.
$this->loadRoutesFrom(__DIR__ . '/routes/web.php');
// Register views.
$this->loadViewsFrom(__DIR__ . '/resources/views', 'my-package');
// Publish assets.
$this->publishes([
__DIR__ . '/resources/assets/' => public_path('vendor/my-package'),
], 'assets');
// Publish assets.
$this->publishes([
__DIR__ . '/migrations' => database_path('migrations'),
], 'migrations'); // <- The tag is defined here will be used in `php artisan vendor:publish --tag=HERE` command.
// Register commands.
if ($this->app->runningInConsole()) {
$this->commands([
ExampleCommand::class,
]);
}
}
public function register()
{
// Merge configuration.
$this->mergeConfigFrom(
__DIR__ . '/config/my-package.php',
'my-package'
);
}
}
Some explanation:
$this->loadRoutesFrom / $this->loadViewsFrom / $this->loadMigrationsFrom
: These lines tells to Laravel that my package has some route/view/migration definitions in those files... So load them into your application.$this->publishes
: This lines copies files/folders from our package's resources/migration/route directory to the Laravel app's folders. That's all!public_path('vendor/my-package')
: This will copy files fromresources/assets
(inside our new package) topublic/vendor/my-package
of consumer/app.
14- Create a manual/help file
It is best to create a README.md file to help users of your package with following sections: about, installation, publishing, configurations, migrations, commands, usage, license etc...
15- Build our package
To make our package ready, go to package's root directory and run the following commands:
composer install
^ Installs package dependencies.
composer dump-autoload
^ Update autoloader after adding new classes.
16- Test/Use our package (locally)
For this, we create a new Laravel application to use/consume our Laravel package.
So let's create a new Laravel application:
composer create-project "laravel/laravel:10.*" my-laravel-app
Now open application's manifest file composer.json, and add the following lines:
"repositories": [
{
"type": "path",
"url": "../myfolder/my-package"
}
]
In this file, we tell Composer about an additional package repository (other than Packagist.org) that is stored locally on the system. Composer will use this repository to find and install packages... so URL must be correct & address our package to the application.
Then normally install our package inside this new Laravel app:
composer require example/my-package
And update autoloader after adding new classes: (app)
composer dump-autoload
So our package is added into the application, but NOT published(copy its stuff) yet.
To verify our package's service provider is loaded in Laravel application: (app)
php artisan package:discover
It must give you something like this: (app)
example/my-package ............................... DONE
laravel/sail ............................................... DONE
laravel/sanctum ........................................ DONE
laravel/tinker ............................................ DONE
nesbot/carbon ........................................... DONE
nunomaduro/collision ................................ DONE
nunomaduro/termwind ............................... DONE
spatie/laravel-ignition ................................. DONE
Now run the following commands to publish/copy our package config/assets/migrations inside the application: (app)
php artisan vendor:publish --tag=config
php artisan vendor:publish --tag=assets
php artisan vendor:publish --tag=migrations
Finally, run application's migrations(if any) then clear ALL caches: (app)
php artisan migrate
php artisan optimize:clear
Best practices
Here are a few short best practices when creating a package:
Testing: Always write unit tests, using PHPUnit or Pest libraries.
Documentation: Include a detailed README.md file in your package's root directory. (Add Overview, Installation, Configuration, Usage, Testing, Contributing...)
Versioning: Use SemVer or any other versioning standard (Major.Minor.Micro.Build).
PSR standards compliance: Follow PSR-12 coding standards.
Security: Validate inputs in middleware/controllers and use CSRF protection.
Publish your Laravel package
Once your Laravel package is complete, tested, and ready for public use, you can submit it to Packagist.org , the official PHP package repository for Composer tool. This allows developers around the world to install your package via a simple command:
composer require example/my-package
Conclusion
Packages streamline Laravel development by promoting reuse and modularity. Follow this guide to create, test, and share your own! Contribute to open-source and avoid "dependency hell" by requiring only essential illuminate/*
components.