Creating Your First Laravel Package: A Step-by-Step Guide

Published on August 12th, 2024 by Akshit Arora

Laravel is a powerful PHP framework that offers a wide range of features out of the box. However, sometimes you might need functionality that isn't included in the core framework. This is where Laravel packages come in handy. In this blog post, we'll walk through the process of creating your own Laravel package.

What is a Laravel Package?

A Laravel package is a way to add functionality to Laravel applications in a modular and reusable manner. It can include routes, controllers, views, configuration files, and more.

When/Why to create a Laravel Package?

A package can be created in 2 cases. If you want to share any kind of functionality in other projects, you may opt-in for creating packages so that your code is re-usable

Secondly, when you want to make some functionality optional in a project, you may provide that functionality as a package.

Steps to Create a Laravel Package

Pre-requisites:

  1. You must have PHP installed in your system
  2. You must have composer installed. Get it from GetComposer

1. Set Up Your Package Structure

First, create a new directory for your package. Then run composer init It will start a wizard to set up your library

This command will guide you through creating your composer.json config.

Package name (<vendor>/<name>) [akshitarora/mypackage]: akshitarora/blogposts

Replace the akshitarora/blogposts with the the name you want to give to your library. Keep on filling the information being asked. The default values will be shown in [] if you ignore the prompt:

Description[]:
Author [Akshit Arora <hello@akshitarora.dev>, n to skip]:
Minimum Stability []: stable
Package Type (e.g. library, project, metapackage, composer-plugin) []: lilbrary
License []: MIT

Define your dependencies.

Would you like to define your dependencies (require) interactively [yes]? no
Would you like to define your dev dependencies (require-dev) interactively [yes]? no
Add PSR-4 autoload mapping? Maps namespace "Akshitarora/Blogposts" to the entered relative path. [src/, n to skip]:

{
    "name": "akshitarora/blogposts",
    "autoload": {
        "psr-4": {
            "Akshitarora\\Blogposts\\": "src/"
        }
    },
    "authors": [
        {
            "name": "Akshit Arora",
            "email": "hello@akshitarora.dev"
        }
    ],
    "require": {}
}

Do you confirm generation [yes]?
Generating autoload files
Generated autoload files
PSR-4 autoloading configured. Use "namespace Akshitarora\Blogposts;" in src/
Include the Composer autoloader with: require 'vendor/autoload.php';

If you want to dive deeper on composer.json properties, check out the official documentation

This will create two folders in your package src and vendor

A typical structure might look like this:

blogposts/
├── src/
├── vendor/
	└── composer/
    └── autoload.php
├── composer.json

2. Add Laravel package as a dependency

Run the command composer require illuminate/support to add the Laravel package as your dependency. This will help in making the Service Provider for your package.

3. Create a Service Provider

Create a Service Provider file in src folder. Taking the reference of my package, I am setting the name as BlogpostServiceProvider.php

In src/BlogpostServiceProvider.php:

<?php

namespace Akshitarora\Blogpost;

use Illuminate\Support\ServiceProvider;

class BlogpostServiceProvider extends ServiceProvider
{
    public function register()
    {
        // Register your package's services here
    }

    public function boot()
    {
        // Bootstrap your package here
    }
}

Now add the service package in composer.json

"extra": {
        "laravel": {
            "providers": [
                "YourVendorName\\YourPackageName\\YourPackageServiceProvider"
            ]
        }
    }

4. Develop Your Package Functionality

Add your package's core functionality. This might include:

  • Creating routes in routes/web.php
  • Adding controllers in src/Controllers/
  • Creating views in resources/views/
  • Adding migrations in database/migrations/

5. Add Configuration (Optional)

If your package needs configuration, create a config/my-package.php file:

<?php

return [
    'key' => 'value',
];

You may want this configuration to be defined as per the project and allow users to make changes in the configuration values. To make your configuration available outside the vendor folder, add it in the ServiceProvider's boot function:

public function boot()
{
    $this->publishes([
        __DIR__.'/../config/my-package.php' => config_path('my-package.php'),
    ], 'config');
}

6. Write Tests Create tests in the tests/ directory to ensure your package works as expected. You may also need to install the dependencies to run your tests. Just make sure you add these dependencies as dev

7. Document Your Package

Write a comprehensive README.md file explaining how to install and use your package.

8. Version Control

Initialize a Git repository and commit your code.

9. Publish Your Awesome Package To Make It Available Globally Push your package to GitHub and then publish it on Packagist for easy installation via Composer.

Conclusion

Creating a Laravel package is a great way to modularize your code and share functionality across projects. By following these steps, you can create a well-structured, reusable package that adheres to Laravel's best practices.

Remember, the key to a good package is not just functionality, but also documentation, tests, and maintainability. Happy coding!