<?php
namespace VendorName\PackageName;
use Illuminate\Support\ServiceProvider;
class MyPackageServiceProvider extends ServiceProvider
{
public function register(): void
{
// Merge config
$this->mergeConfigFrom(
__DIR__.'/../config/mypackage.php',
'mypackage'
);
// Bind services
$this->app->singleton(MyService::class, function ($app) {
return new MyService($app['config']['mypackage']);
});
}
public function boot(): void
{
// Publish config
$this->publishes([
__DIR__.'/../config/mypackage.php' => config_path('mypackage.php'),
], 'config');
// Publish migrations
$this->publishes([
__DIR__.'/../database/migrations' => database_path('migrations'),
], 'migrations');
// Load migrations
$this->loadMigrationsFrom(__DIR__.'/../database/migrations');
// Load routes
$this->loadRoutesFrom(__DIR__.'/../routes/web.php');
// Load views
$this->loadViewsFrom(__DIR__.'/../resources/views', 'mypackage');
// Publish views
$this->publishes([
__DIR__.'/../resources/views' => resource_path('views/vendor/mypackage'),
], 'views');
// Register commands
if ($this->app->runningInConsole()) {
$this->commands([
Commands\MyCommand::class,
]);
}
}
}
{
"name": "vendorname/packagename",
"description": "A Laravel package description",
"type": "library",
"require": {
"php": "^8.1",
"illuminate/support": "^10.0"
},
"require-dev": {
"orchestra/testbench": "^8.0",
"phpunit/phpunit": "^10.0"
},
"autoload": {
"psr-4": {
"VendorName\\PackageName\\": "src/"
}
},
"autoload-dev": {
"psr-4": {
"VendorName\\PackageName\\Tests\\": "tests/"
}
},
"extra": {
"laravel": {
"providers": [
"VendorName\\PackageName\\MyPackageServiceProvider"
],
"aliases": {
"MyPackage": "VendorName\\PackageName\\Facades\\MyPackage"
}
}
},
"minimum-stability": "dev",
"prefer-stable": true
}
<?php
namespace VendorName\PackageName\Tests;
use Orchestra\Testbench\TestCase as Orchestra;
use VendorName\PackageName\MyPackageServiceProvider;
class TestCase extends Orchestra
{
protected function getPackageProviders($app)
{
return [
MyPackageServiceProvider::class,
];
}
protected function getEnvironmentSetUp($app)
{
// Setup test environment
$app['config']->set('database.default', 'testing');
$app['config']->set('mypackage.option', 'value');
}
}
Creating Laravel packages enables code reusability across projects. I structure packages with src/ for code, config/ for configuration, and database/ for migrations. Service providers register package components—routes, views, commands, configs. The publishes() method lets users customize assets. Auto-discovery automatically registers providers in Laravel 5.5+. Packages define dependencies in composer.json. I test packages independently with Orchestra Testbench. The loadRoutesFrom(), loadViewsFrom(), and loadMigrationsFrom() methods integrate package resources. For distribution, I publish to Packagist. Package development promotes modularity and open-source contribution.