Back to Course |
How to Create Laravel Package: Step-by-Step Example

Create Package: Structure & composer.json

There are a few ways to start developing the package, there are a few popular skeleton repositories like this one from Spatie.

But for this particular tutorial, I want to explain how it all works inside, so you may use skeletons for your future packages, but not the first one.

What I'm suggesting for the beginning is that we create a new Laravel project (not a package), and then we will "fit" our package inside of it, as a subfolder, "faking" it to work via composer.

  • Create a new Laravel project with laravel new project (or another command if you prefer)
  • Inside that project, create a folder /packages/laraveldaily/laravel-permission-editor

This is exactly what I will call our package. The name of the package consists of two parts: vendor/package-name, so our vendor (creator) is laraveldaily (a real username on GitHub) and the actual package will be called laravel-permission-editor.

Laravel package folder

Next, we need to create or generate a composer.json file in the main folder of our package. Composer has a command for that composer init which will launch a wizard with a set of questions that we just answer, and then it generates the composer.json file.

cd packages/laraveldaily/laravel-permission-editor
composer init

To be honest, it doesn't matter that much what you will specify in that composer wizard because you would be able to easily change everything later. It will matter when publishing the package, so we will re-review this file much later, anyway.

For now, I will start with these values:

packages/laraveldaily/laravel-permission-editor/composer.json:

{
"name": "laraveldaily/laravel-permission-editor",
"description": "Visual UI for managing Roles/Permissions for Spatie Laravel Permission package",
"license": "MIT",
"authors": [
{
"name": "Povilas Korop",
"email": "povilas@laraveldaily.com"
}
],
"minimum-stability": "dev",
"require": {}
}

Next, we need to load that package into our main composer.json file, the one that is in the Laravel project and not in the packages/ folder.

We add the package with the dev-main branch as a requirement:

composer.json

// ...
"require": {
"php": "^8.0.2",
"guzzlehttp/guzzle": "^7.2",
"laravel/framework": "^9.19",
"laravel/sanctum": "^3.0",
"laravel/tinker": "^2.7",
"laraveldaily/laravel-permission-editor": "dev-main"
},
"repositories": [
{
"type": "path",
"url": "packages/laraveldaily/laravel-permission-editor",
"options": {
"symlink": true
}
}
],

And we run composer update in our main project. Would it find our package?

In case of success, among the update lines, you should see this one:

  • Installing laraveldaily/laravel-permission-editor (dev-main): Symlinking from packages/laraveldaily/laravel-permission-editor

Great, so our Laravel project sees the package now! We can start working on the functionality.