Scaffold a Laravel Package In 4 Easy Steps

Photo by Ricardo Gomez Angel / Unsplash

1.  Create the file structure

We are going to create 4 directories and 2 files. In this example my "company" is going to be called "testcompany" and my package will be "test-package"

  • Create a directory called "packages" in your Laravel application
  • Create a "company" directory in the "packages" directory
  • Create your actual "package" directory in the "company" directory
  • Create a "src" directory in your "package" directory
  • Create a ServiceProvider file in your "src" directory. You can name this after your package
  • In your "package" directory create a composer.json file

2. Populate the two neccessary files

ServiceProvider: Extend the Laravel ServiceProvider and add a boot method and a register method

<?php

namespace TestCompany\TestPackage;

use Illuminate\Support\ServiceProvider;

class TestPackageServiceProvider extends ServiceProvider
{
    public function boot()
    {
		//
    }

    public function register()
    {
		//
    }
}
TestPackageServiceProvider.php

Composer file: You'll need a few things here so Laravel knows where to look for the package logic. You can also run composer init in the package root and composer will guide you through the initital setup. You will still need to provide the "autoload" and "extra" objects seen here

{
    "name": "testcompany/test-package",
    "description": "My very first package",
    "require": {
    },
    "autoload": {
        "psr-4": {
            "TestCompany\\TestPackage\\": "src/"
        }
    },
    "extra": {
        "laravel" : {
            "providers": [
                "TestCompany\\TestPackage\\TestPackageServiceProvider"
            ]
        }
    }
}
composer.json

3. Update your Laravel Application's composer.json (not your package's composer.json)

Under the "keyword" property and a new property "repositories". Then you'll want to reference it like so--

    "repositories": {
        "test-package": {
            "type": "path",
            "url":  "packages/testcompany/test-package",
            "options": {
                "symlink": true
            }
        }
    },
Repositories JSON object in primary composer.json

And you need to add it to your required object. Since there are no versions yet, you can set the version to @dev

"require": {
	"testcompany/test-package": "@dev"
}
The new line that needs to be added to your primary composer.json require JSON object

4. Run composer install in your Laravel app

The final step! Run composer update and you will now find your package in your vendors directory!

Congratulations! You just created your very first Laravel package!

If you are ready for the next step and want to make your package open source and promote it, check out this guide!

If you prefer to consume your content via video Andrew Schmelyun (https://twitter.com/aschmelyun) has a good straight to the point video about creating a package for Laravel