Courses

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

Create and Register the Service Provider

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.

php 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:

namespace Laraveldaily\LaravelPermissionEditor;
 
use Illuminate\Support\ServiceProvider;
 
class PermissionEditorServiceProvider extends ServiceProvider
{
public function register()
{
//
}
 
public function boot()
{
//
}
}

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:

{
"name": "laraveldaily/laravel-permission-editor",
 
// ...
 
"autoload": {
"psr-4": {
"Laraveldaily\\LaravelPermissionEditor\\": "src"
}
},
"extra": {
"laravel": {
"providers": [
"Laraveldaily\\LaravelPermissionEditor\\PermissionEditorServiceProvider"
]
}
},
}

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

No comments or questions yet...