Courses

NEW! How to Create Laravel Package: Step-by-Step Example

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.

1cd packages/laraveldaily/laravel-permission-editor
2composer 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:

1{
2 "name": "laraveldaily/laravel-permission-editor",
3 "description": "Visual UI for managing Roles/Permissions for Spatie Laravel Permission package",
4 "license": "MIT",
5 "authors": [
6 {
7 "name": "Povilas Korop",
8 "email": "povilas@laraveldaily.com"
9 }
10 ],
11 "minimum-stability": "dev",
12 "require": {}
13}

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

1// ...
2"require": {
3 "php": "^8.0.2",
4 "guzzlehttp/guzzle": "^7.2",
5 "laravel/framework": "^9.19",
6 "laravel/sanctum": "^3.0",
7 "laravel/tinker": "^2.7",
8 "laraveldaily/laravel-permission-editor": "dev-main"
9},
10"repositories": [
11 {
12 "type": "path",
13 "url": "packages/laraveldaily/laravel-permission-editor",
14 "options": {
15 "symlink": true
16 }
17 }
18],

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.

No comments or questions yet...