How To Use Composer To Create A Laravel Package?

Laravel is one of the most popular PHP frameworks, and its modular structure makes it easy to extend
functionality through packages. This guide walks you through creating a Laravel package using Composer.

1. What is Composer?

Composer is a dependency manager for PHP that allows you to manage libraries and packages in your projects.
It simplifies the process of adding, updating, and managing dependencies.

2. Steps to Create a Laravel Package

Step 1: Set Up Your Environment

Ensure you have Composer and Laravel installed on your system. You can install Composer from
here, and set up Laravel using Composer:

composer create-project laravel/laravel example-app

Step 2: Create a Package Folder

Inside your Laravel project, create a directory for your package. For example:

mkdir packages/YourName/YourPackage

Step 3: Initialize Composer in the Package

Navigate to your package folder and run the following command:

composer init

Follow the prompts to set up your package's metadata (name, description, license, etc.).

Step 4: Write the Package Code

Create a src folder inside your package directory and add the core functionality of your
package. For example:


packages/YourName/YourPackage
├── composer.json
└── src
    └── ExampleClass.php
        

Example ExampleClass.php:

namespace YourName\YourPackage;

class ExampleClass {
    public function sayHello() {
        return "Hello from YourPackage!";
    }
}

Step 5: Autoloading

Update your package's composer.json to include autoloading:

{
    "autoload": {
        "psr-4": {
            "YourName\\YourPackage\\": "src/"
        }
    }
}

Run composer dump-autoload to regenerate the autoload files.

Step 6: Register the Package in Laravel

Add your package's service provider in the config/app.php file if required. Alternatively, use
auto-discovery by defining the provider in the package's composer.json:

{
    "extra": {
        "laravel": {
            "providers": [
                "YourName\\YourPackage\\YourServiceProvider"
            ]
        }
    }
}

Step 7: Publish Your Package

To share your package, push it to a public Git repository (e.g., GitHub) and submit it to
Packagist by linking your repository.

Conclusion

Creating Laravel packages with Composer is a powerful way to modularize and reuse your code. With this
guide, you can develop your package and share it with the community.

Ready to Create Your Own Laravel Package with Composer?

Let Logieagle guide you through building, structuring, and publishing reusable Laravel packages with confidence.

Contact Logieagle Today