This is a AI-generated post, and it may have some mistakes. I'll update the post later with well-thought content.
Creating a Laravel package allows you to reuse code across multiple projects. Here is the concise process to build a simple local package.
1. Create the Directory Structure Create a packages folder in your Laravel root, followed by your vendor and package name.
mkdir -p packages/yourvendor/yourpackage/src2. Initialize Composer Navigate to your package directory and initialize it.
cd packages/yourvendor/yourpackage
composer initFollow the prompts. Make sure to define your PSR-4 autoloading in the generated composer.json:
"autoload": {
"psr-4": {
"YourVendor\\YourPackage\\": "src/"
}
}3. Create the Service Provider Create YourPackageServiceProvider.php inside the src folder. This is the entry point for your package.
<?php
namespace YourVendor\YourPackage;
use Illuminate\Support\ServiceProvider;
class YourPackageServiceProvider extends ServiceProvider
{
public function boot()
{
// Load routes, views, or migrations here
$this->loadRoutesFrom(__DIR__.'/routes/web.php');
}
public function register()
{
// Bind things into the container here
}
}4. Add a Simple Route Create src/routes/web.php to test if the package works.
<?php
use Illuminate\Support\Facades\Route;
Route::get('/package-test', function () {
return 'My Laravel package is working!';
});5. Register the Package in Your Main App Open your Laravel project's root composer.json and add your package to the psr-4 autoload block:
"autoload": {
"psr-4": {
"App\\": "app/",
"YourVendor\\YourPackage\\": "packages/yourvendor/yourpackage/src/"
}
}Run composer dump-autoload to regenerate the class maps.
Finally, register your service provider in bootstrap/providers.php (Laravel 11) or config/app.php (Laravel 10 and below):
YourVendor\YourPackage\YourPackageServiceProvider::class,Visit /package-test in your browser to see your package in action.
