Creating and using Laravel packages allows you to organize and share reusable code in your Laravel applications. Laravel packages are typically distributed through Composer, making it easy to manage dependencies. Here's a step-by-step guide on how to create and use Laravel packages:
Create a New Laravel Package:
Use the Laravel package development tool to scaffold a new package. Open a terminal and run the following command, replacing vendor/package
with your desired vendor and package name:
composer create-project --prefer-dist laravel/laravel vendor/package |
This will create a new Laravel package skeleton.
2. Navigate to the Package Directory: Change your current directory to the newly created package:
cd vendor/package |
1. Create Package Files: Add your package files, such as controllers, models, views, and any other files needed for your functionality.
2. Define Service Providers:
If your package requires service providers, create them in the src
directory. Register these providers in the src/ServiceProvider.php
file.
3. Define Configuration:
If your package requires configuration, create a configuration file in the config
directory and load it in your service provider.
4. Define Routes:
If your package has routes, define them in the routes
directory and load them in your service provider.
1. Composer Autoloading:
Make sure your package classes are autoloaded using the Composer autoloader. You can achieve this by adding the following to your composer.json
file:
"autoload": { "psr-4": { "Vendor\\Package\\": "src/" } }, |
Then, run composer dump-autoload
to regenerate the Composer autoloader.
1. Write Tests:
Create PHPUnit tests for your package in the tests
directory.
2. Run Tests: Execute your tests to ensure your package works as expected:
composer test |
php artisan vendor:publish --tag=package-name |
1. Add Package to composer.json
:
Open your Laravel application's composer.json
file and add your package to the require
section:
"require": { "vendor/package": "dev-main" }, |
Run composer install
to install the package.
config
directory in your Laravel application after running composer install
. Modify the configuration as needed.providers
array in the config/app.php
file.That's it! You've created and used a Laravel package. Remember to follow best practices and consider providing documentation for your package to make it easy for others to use.
=== Happy Coding :)