Courses

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

Every package needs to have the main Service Provider to load all the configurations and extra things.

You can name that file however you want, typically using CamelCase and "ServiceProvider" at the end.

Since Laravel has a make:provider Artisan command, what I personally like to do is generate the Service Provider in the main folder of the project, and then move that file to the packages/ folder, changing the namespace as well.

1php artisan make:provider PermissionEditorServiceProvider

This generates the file in app/Providers but I move it to the packages/ folder, creating a new src subfolder:

packages/laraveldaily/laravel-permission-editor/src/PermissionEditorServiceProvider.php:

1namespace Laraveldaily\LaravelPermissionEditor;
2 
3use Illuminate\Support\ServiceProvider;
4 
5class PermissionEditorServiceProvider extends ServiceProvider
6{
7 public function register()
8 {
9 //
10 }
11 
12 public function boot()
13 {
14 //
15 }
16}

Now, where does that namespace come from? We need to register the namespace and the provider itself, in the package composer.json file, adding the new autoload and extra sections:

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

1{
2 "name": "laraveldaily/laravel-permission-editor",
3
4 // ...
5
6 "autoload": {
7 "psr-4": {
8 "Laraveldaily\\LaravelPermissionEditor\\": "src"
9 }
10 },
11 "extra": {
12 "laravel": {
13 "providers": [
14 "Laraveldaily\\LaravelPermissionEditor\\PermissionEditorServiceProvider"
15 ]
16 }
17 },
18}

Again, for now, we haven't created any functionality, right?

No comments or questions yet...