Step by Step Guide to Custom Laravel Package Development

Introduction:

Since its introduction on June 9, 2011 – Laravel has been the fastest-raising PHP framework used by 46,000+ developers across the world, with its advanced integrated features and in-built CSRF token security Laravel is trusted and in use on 7,61,321+ websites.

Not only this, but Laravel also plays an important role in huge multinational companies such as BBC, TourRadar, 9GAG, Razorpay, and many others. With its boosted accessibility Laravel demand will be crazily growing in upcoming years and each of us should be prepared for it.

In nutshell, the developers are also gravitating towards Laravel – as per the survey coders have found that the PHP framework has eased down their development complexities, with offerings of more functionalities, and also optimised security which is the most important checkpoint for each business.

Regardless of Laravel’s 20 in-built libraries and modules, the rise of Laravel Package is also growing as it is a great way to store a bunch of reusable and easily shareable code – of which you might have already come across.

The addition of your code into a package and making it accessible to others is what gets named a Custom Laravel Package – you can include functionality, controllers, routes, views, and many other configurations that can be helpful for you and others in giving Laravel applications an improvement edge.

So, let’s move ahead and get on the steps to create a custom Laravel Package.

These will be 7 easy steps guiding you through a brief process of creating an optimised and useful Custom Laravel package that will be easily accessible to others with the installation process to carry out via composer.

Custom Laravel Package Development in 7 Easy Steps

1. Creation Of A New Folder In The Laravel Package

First of all, the first step will include the installation of Laravel on your pc/laptop.

After the installation steps are completed, you would need to add a new folder under the root of the app.

Then it comes to naming the folder inside the package, which can be as per your personal choice. For example, it can be the business/vendor’s name you are creating the package for – As of now let’s keep it “horizoncore”.

Then under the same folder, create another folder with the name of your package as calc. Okay, coming to the last folder to add now which you name as ‘src’ – the file with which many of us are aware of, it stands for the source file where the code of the package will lie.

Please don’t forget to check out the structure at last, which should be like this; ‘packages/horizoncore/calc/src’.

2. Naming And Initialising The Folder

For this you would need to hop on the command prompt and navigate to the folder with the exact package name; ‘packages/horizoncore/calc/src’.

Then run the command mentioned below;
Composer init

This step will be initiating the current folder add a composer package, but during the process, there will be a series of crucial questions that will be asked to you for completing the package setup.

If you are not aware of any questions during the installation steps, you can simply skip them by pressing enter as this is available as addable and editable elements which can also get done later.

After the setup is completed successfully, a new file named “composer.json” will be reflected in the package folder. This configuration file gets rooted under every PHP file, it basically contains information regarding your application data and needs.

To know how your composer.json file will look, you can check the reference below, as the initialising process is completed you can move to give the command to the main app ‘composer.json’ to load it.

    {
        "name": "horizoncore/calc",
       "description": "Different calculation function",
        "authors": [
            {
                 "name": "Example",
                "email": "example@horizoncore.com"
            }
        ],
        "minimum-stability": "mono"
    }

3. Loading The Package From The composer.json File

Just like other PHP frameworks, in the Laravel application also the composer.json file is at the root. As composer.json is the main file, there is only here you have to code define your all dependencies.

Let’s give it a start by autoloading of the created package via the autoload block:

    "autoload": {
        "classmap": [
    ...
        ],
        "psr-4": {
            "App\\": "app/",
            "horizoncore\\calc\\": "packages/horizoncore/calc/src/"
        }

To run the autoloader and autoload the package, you would need a composer – which you’ll be able to access after running the code below:

composer dump-autoload

Then there will be another command (mentioned below) which is needed to run for optimising the class loader, you won’t be doing it every time but as this for the first time, the code is necessary to run:

Php artisan optimise

4. Adding Package Service Provider

This service provider can be defined as the main entrance for getting into the package in PHP’s management system where your custom package will be loaded. This ServiceProvider will be created at the root of your app with the command line of the artisan command; i.e.

php artisan make:provider CalcServiceProvider

After its process gets completed, you’ll find a new file located at:

app/Providers/CalcServiceProvider.php

The next step will include moving this file into the package folder, the location will be:

packages/horizoncore/calc/src/CalcServiceProvider.php

Don’t miss out to change your namespace to be:

`Vendor\Package_name`.

As the window will be prompt, you’ll get to see a new service provider class in which there will be 2 methods; boot() and register().

boot() – it is a public function used to boot routes or any other functionalities you would like to add to your custom Laravel Package depending on the service provider’s boot method.

register() – Procedure used for binding of classes or functionality in the app container.

Next and the last step of this pointer will be the addition of a new ServiceProvider in the large bracket – [] array mentioned in config/app.php:

    providers' => [
        /*
         * Application Service Providers...
        */
        ...
        App\Providers\RouteServiceProvider::class,
         horizoncore\calc\CalcServicesProvider::class,
    ],

5. Adding routes.php File In Your Package

Which will be accomplished by creating new routes.php in the package src dictionary, you can simply copy and paste the below-shown code also;

    Route::get(‘calc', function(){
        echo 'Hello from the Calc package!';
    });
    After this include the routes.php file inside the boot() method of the service provider’s boot method.
    public function boot()
    {
        //
        include __DIR__.'/routes.php';
    }

When you’ll run the application by considering the route name calc, the following output will be obtained by you;

Hello from the Calc package!

6. Creating A Package Controller

Run the artisan command

php artisan make:controller CalcController

Then move the controller from

app/Http/Controllers/CalcController.php

To

packages/horizoncore/calc/src/CalcController.php.

In this controller, create 2 methods; add() and subtract(), with which the file will be looking like this;

    php
    namespace horizoncore\Calc;
    use Illuminate\Http\Request;
    use App\Http\Requests;
    use App\Http\Controllers\Controller;
    class CalcController extends Controller
    {
        //
        public function add($a, $b){
            echo $a + $b;
        }
        public function subtract($a, $b){
            echo $a - $b;
        }
    }

Addition of a few more routes and this step will be covered in less than a minute now.

    Route::get('add/{a}/{b}',
    'Horizon\Calc\CalcController@add');
    Route::get('subtract/{a}/{b}',
    'horizoncore\Calc\CalcController@subtract');

After this, navigate to the links below – there will be a little surprise awaiting you.

http://localhost:8000/add/5/2

http://localhost:8000/subtract/5/2

(On the first link, you’ll get to see the result: 7)

(On the second link, you’ll get to see the result: 3)

7. Addition Of Views To Your Custom Laravel Project

In the src folder of your packages, create another folder named views, and creation of a new file named add.blade.php, Add the below-mentioned code to it;

Then move to the registration process where these views will be loaded which is by the ServicePorvider method by adding a new code

    public function register()
    {
        // register our controller
        $this->app->make('horizoncore\Calc\CalcController');
        $this-> loadViewsFrom(__DIR__.'/views', 'calc');
    }

    public function add($a, $b){
        $result = $a + $b;
        return view('calculator::add', compact('result'));
    }

If we load up the following URL http://localhost:8000/add/5/2 in our browser we’ll end up with the following:

To call out this views, let’s change the add() function inside of the Calculator controller:

    public function add($a, $b){
        $result = $a + $b;
        return view('calculator::add', compact('result'));
    }

After this, if you’ll load the http://localhost:8000/add/5/2 in the browser – you’ll be ending with the screen showing:

Your result 7

And here we are completed with the development of your Custom Laravel Package in easy 7 steps

Kudos! You Did A Great Job.

And that’s it for now, with us you learned the development of Custom Laravel Package With Easy 7 Steps which was very easy for you for sure. If you go through the steps precisely, we bet you’ll be ending up with a perfect setup.

Even though let’s not omit the twining of coding and errors, so if you get in stuck in between any of those feel free to contact us at www.horizoncore.com and discuss your Custom Laravel Package requirements -our experienced team will be right there to help out and roll the project requirements at its best.

karan-vala
Karan Vala

Project Manager with 6 years of experience in Project Initiation, Planning & Delivery. Enthusiastics in taking up challenging roles and consistently achieving high quality result. Highly organized individual with good problem solving skills and strong interpersonal communication

Get in Touch