Introduction

A Laravel package is a set of reusable classes that improve the functionality of a Laravel website. To put it another way, a package is what WordPress plugins are. Laravel packages are designed to reduce development time by encapsulating reusable functionality in a set of stand-alone classes that can be used in any Laravel project.

In this tutorial: How to Build Laravel Package using Composer, we’ll construct a Laravel package for a contact form. Let’s get this party started.

Prerequisite to Build Laravel Package using Composer

Here are the prerequisites to build Laravel package using Composer:

  • Laravel v 5.5 or above is required.
  • Composer installed on your system. You may get Composer here if you don’t already have it.

Basic Set-Up and Installation

Because a package is designed to give more functionality to a Laravel website, the first step is to construct a Laravel website. We’ll use Composer to set it up. Check out the official Laravel documentation for more installation options.

Copy Text
$ composer create-project —prefer-dist laravel/laravel packagetestapp

You’ll need to configure your env file and specify your app key and other relevant data after that’s done. Use the following command in your terminal or manually transfer the contents of the .env.example to a new file and save it as .env.

Copy Text
$ cp .env.example .env

Once done, use the below command.

Copy Text
$ php artisan key:generate

Your .env should look like this once you’ve generated your app key and configured your database details.

Basic Set-Up

Our basic Laravel app is now set up. It’s time to start working on our package.

Develop high-performance Laravel applications with Bacancy!
Hire Laravel Developer and witness the building of your dream product with us. We have dedicated developers with extraordinary problem skills. Contact us today!

Project Structure

We’ll set up the fundamental essentials of our package. There are essentially two methods for accomplishing this:

  • Manually generating individual files and folders
  • Utilizing a package such as this CLI utility.

Here, we will manually generate the files and directories to understand how each component fits together.

Here is our package’s folder structure.

Create folders with the following structure from your root directory.

Copy Text
$ packages/YourVendor/YourPackage/

Because it’s not a good practice to update the code in the vendor folder, we’ll perform all of our work outside in the packages/YourVendor/YourPackage/ directory instead of vendor/YourVendor/YourPackage/.

When we’re finished releasing our package, it’ll be available for download under the vendor folder.

YourVendor is the name of the vendor, which might be your name or the name of the customer or business for whom you are generating the package.

The package name is represented by YourPackage. It will be contactform in our instance.

Let’s begin creating the files and folders that will comprise our package.

Copy Text
YourVendor
   └── contactform
       └── src
           ├── Database
           │   └── migrations
           ├── Http
           │   └── controllers
           ├── Models
           ├── resources
           │   └── views
           └── routes

Create Composer File

We’ll initialize the Composer now. Use the below command to generate composer.json.

Copy Text
$ composer init

Because it is interactive, it will ask you a series of questions to fill up your composer.json file. If you’re unsure, click enter to use the default response; if you’re not sure, you may update it later directly from the composer.json file.

The composer.json file should now look like this.

Copy Text
{
   "name": "YourVendor/Contactform",
    "description": "A contact form package for laravel",
    "authors": [{
       "name": "Usama Patel",
       "email": "[email protected]"
  }],
    "require": {}
}

We need to inform composer.json to autoload our files, so add this code to your composer.json.

Copy Text
"autoload": {
    "psr-4": {
     "YourVendor\\contactform\\": "src/"
    }
 }

Our composer.json file should now look something like this.

Copy Text
{
    "name": "YourVendor/Contactform",
    "description": "A contact form package for laravel",
    "authors": [{
       "name": "Usama Patel",
        "email": "[email protected]"
     }],
    "require": {},
    "autoload": {
    "psr-4": {
         "YourVendor\\Contactform\\": "src/"
      }
    }
  }

Create an empty git repository to keep track of modifications after that (we’ll add the remote repo later). Use the below command.

Copy Text
$ git init

Create Service Provider

Let’s start by adding some files to our package. To begin, we must identify a service provider for our package. Laravel utilizes a service provider to figure out which files will be loaded and accessible by your package.

Create a ContactFormServiceProvider.php file in your src/subdirectory

Copy Text
$ src/ContactFormServiceProvider.php

We need to define a few items within our service provider:
1. The namespace (which we defined in our composer.json autoload).
2. The extension (the Laravel class which our service provider extends)
3. The two mandatory methods that every service provider must have (at least two methods are required for every Laravel package service provider: boot() and register()).

Add the following lines of code to your service provider class.

Note: You may replace YourVendor with your own vendor name in the code below.

// ContactFormServiceProvider.php

Copy Text
<?php
   
    namespace YourVendor\contactform;
    use Illuminate\Support\ServiceProvider;
    class ContactFormServiceProvider extends ServiceProvider {
        public function boot()
        {
        }
        public function register()
        {
      }
   }
?>

We need to inform Laravel how to load our package and utilize its functionalities because we haven’t deployed it and it isn’t yet within our vendor folder, so inside the root of your Laravel project in the composer. Add the following code to your JSON.

Copy Text
"autoload": {
    "classmap": [
     "database/seeds",
     "database/factories"
    ],
      "psr-4": {
          "YourVendor\\Contactform\\":     "packages/YourVendor/contactform/src",
          "App\\": "app/"
         }
      },
       "autoload-dev": {
           "psr-4": {
              "YourVendor\\Contactform\\": "packages/YourVendor/contactform/src",
              "Tests\\": "tests/"
            }
        },

Depending on your Laravel version, Laravel may add it for you automatically. If it does, be sure to skip it.

Then, on your terminal, run the following command at the root of your app.

Copy Text
$ composer dump-autoload

Let’s check to verify if our package is loaded appropriately now. Let’s create a route and load it in the startup method of the ContactFormServiceProvider.php file.

// ContactFormServiceProvider.php

Copy Text
$this->loadRoutesFrom(__DIR__.'/routes/web.php');

Please take notice of the following:

  • The current directory where the file is located is referred to as __DIR__.
  • The routes folder we’ll construct for our package, which will exist in our src folder, not the default Laravel routes, is referenced in routes/web.php.

Add the following code to the web.php file in our package routes folder.

Copy Text
<?php
    // YourVendor\contactform\src\routes\web.php
    Route::get('contact', function(){
        return 'Hello from the contact form package';
    });
?>

Then, in our root config/app.php, we need to add our new service provider to the providers’ array as shown below.

// config/app.php

Copy Text
'providers' => [
     ...,
     App\Providers\RouteServiceProvider::class,
     // Our new package class
     YourVendor\Contactform\ContactFormServiceProvider::class,
 ],

Run the App

Start your Laravel app now by using the command.

Copy Text
php artisan serve

Go to localhost:8000/contact in your browser and you should see something like this:

Run the App

You might want to know

Top Laravel Packages To Install

Github Repository: Laravel Package Example

Now we know our package is loading properly we need to create our contact form. You can find the rest of the code on this Github Repository.

Conclusion

This was a basic tutorial to get started with how can you build Laravel package using Composer. With your newfound understanding, you can create even more amazing packages.

Laravel Tutorials

Polish your technical skills

LEARN NOW

Get In Touch

[email protected]

Your Success Is Guaranteed !

We accelerate the release of digital product and guaranteed their success

We Use Slack, Jira & GitHub for Accurate Deployment and Effective Communication.

How Can We Help You?