Laravel packages are a great way to encapsulate reusable code and share it across multiple projects. They allow you to create standalone components that can be easily integrated into your Laravel applications.
They can be installed via composer into your different applications and share the functionality over the different projects.
In this article, we'll look at how to create a local Laravel package. This is useful for developing a package that you don't want to share with the world or for testing a package before publishing it to Packagist.
This is the process I use when creating a new laravel package, I'd develop it locally within an existing project and encapsulate the code into this package, when I'm happy this is working as expected I can then deploy to packagist and install via composer.
I want to use composer.json locally to make sure that how the package is installed with be the sameway locally as with packagist.
To do this I create a new directory in the root of my project called packages and then create a new directory within this called my-package
.
mkdir -p packages/my-package && cd packages/my-package
Then you need to create a package composer.json file within this directory.
{
"name": "my-vendor/my-package",
"description": "My Package Description",
"type": "library",
"license": "MIT",
"authors": [
{
"name": "Your Name",
"email": ""
}
],
"require": {
"php": "^8.2",
"illuminate/support": "^11.0"
},
"require-dev": {
"phpunit/phpunit": "^10.0"
}
"autoload": {
"psr-4": {
"MyVendor\\MyPackage\\": "src/"
}
},
"autoload-dev": {
"psr-4": {
"MyVendor\\MyPackage\\Tests\\": "tests/"
}
},
"extra": {
"laravel": {
"providers": [
"MyVendor\\MyPackage\\MyPackageServiceProvider"
]
}
},
"minimum-stability": "dev",
"prefer-stable": true,
"config": {
"sort-packages": true
},
"scripts": {
"test": "phpunit"
}
}
We need to tell composer.json about this package in the main project. To do this we will add a repositories key to the main composer.json
file.
{
"repositories": [
{
"type": "path",
"url": "packages/my-package",
"options": {
"symlink": true
}
}
]
}
We can now require the package in the main project.
composer require my-vendor/my-package
You can now start developing your package within the packages/my-package
directory. You can create a new service provider, controllers, models, etc. and use them within your Laravel application.
When you're happy with the package, you can then publish it to Packagist and require it in your other projects.