Introducing

How to create a Laravel package


If you're anything like me, you're probably always searching for ways to cut down on development time. One way to do that is to create your own Laravel packages. In this blog post, I'm going to show you

How to create a Laravel package from scratch.

First, you'll need to create a new directory for your package. I like to keep my packages stored in a "packages" directory at the root of my project. So, for this example, I'll create a new directory called "acme" in my "packages" directory.

Next, you'll need to create a composer.json file in your new directory. This file will tell Composer how to install and load your package.

{
    "name": "acme/my-package",
    "description": "My awesome Laravel package",
    "keywords": ["laravel", "package"],
    "license": "MIT",
    "authors": [
        {
            "name": "John Doe",
            "email": "[email protected]"
        }
    ],
    "require": {
        "php": ">=5.6.0"
    },
    "autoload": {
        "psr-4": {
            "Acme\\MyPackage\\": "src/"
        }
    }
}

In the composer.json file, you'll notice that we're using the

PSR-4 autoloading standard

This means that our package's classes will be loaded from the "src" directory.

Next, you'll need to create a "src" directory and add a "MyPackageServiceProvider.php" file to it. This file will contain your package's service provider class.

<?php

namespace Acme\MyPackage;

use Illuminate\Support\ServiceProvider;

class MyPackageServiceProvider extends ServiceProvider
{
    /**
     * Register any package services.
     *
     * @return void
     */
    public function register()
    {
        //
    }

    /**
     * Bootstrap any package services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }
}

The service provider is the central place to configure your package.

In the register method, you should bind any interfaces to implementations. And in the boot method, you should subscribe to any events that your package needs to respond to.

Next, you'll need to add your service provider to the providers array in your config/app.php file.

'providers' => [
    // Other service providers...

    Acme\MyPackage\MyPackageServiceProvider::class,
],

And that's it! You've now created a basic Laravel package.

Categories:
Tags:
Laravel
How-to
Package
Laravel how to create a package