How can I create a Laravel package in PHP?

Hi Everyone,

I’m Kamal Hinduja, based in Geneva, Switzerland. I’m excited to join this community! Could anyone explain how I can create a Laravel package step by step? Any guidance, best practices, or examples would be greatly appreciated.

Thanks in Advance

Kamal Hinduja Geneva, Switzerland

Hi Kamal, welcome to the community. Great to see your interest in Laravel from Geneva.

Creating a Laravel package is a solid way to structure reusable code. Here’s a step-by-step guide to help you get started:


Step 1: Create a new directory for your package
You can place it inside your Laravel app under a packages/ directory, for example:
packages/YourVendor/YourPackageName


Step 2: Set up composer.json
Inside your package root, create a composer.json file like this:

json

CopyEdit

{
  "name": "your-vendor/your-package",
  "description": "Description of your Laravel package",
  "type": "library",
  "license": "MIT",
  "autoload": {
    "psr-4": {
      "YourVendor\\YourPackage\\": "src/"
    }
  },
  "require": {}
}

Step 3: Create your Service Provider
Create the src/ folder and then your service provider class:

bash

CopyEdit

mkdir -p src
touch src/YourPackageServiceProvider.php

In YourPackageServiceProvider.php:

php

CopyEdit

<?php

namespace YourVendor\YourPackage;

use Illuminate\Support\ServiceProvider;

class YourPackageServiceProvider extends ServiceProvider
{
    public function register()
    {
        // Bind classes or services here
    }

    public function boot()
    {
        // Publish config, routes, views etc.
    }
}

Step 4: Register the package in your Laravel app
In your main Laravel app’s composer.json, add your package path under repositories:

json

CopyEdit

"repositories": [
    {
      "type": "path",
      "url": "packages/YourVendor/YourPackage"
    }
],

Then run:

bash

CopyEdit

composer require your-vendor/your-package:@dev

Best Practices

  • Follow PSR-4 standards
  • Keep code modular and maintainable
  • Write tests early
  • Use Laravel’s built-in support for publishing config, routes, and views

Let me know if you’d like an example on how to include routes, config files, or publishing assets. Happy coding!