Laravel 12 Package Development: Your First Step into Reusable Laravel Code

Author

Kritim Yantra

May 15, 2025

Laravel 12 Package Development: Your First Step into Reusable Laravel Code

Laravel is more than just a framework—it's a complete developer ecosystem. One of the coolest things it offers is package development. With packages, you can create reusable, modular components that make your projects cleaner, more maintainable, and even shareable with the world.

If you’ve ever wondered how developers build Laravel packages, this blog post is for you. Let’s walk through building your first Laravel package from scratch—step by step, the beginner-friendly way.


📦 What Exactly is a Laravel Package?

A Laravel package is a self-contained chunk of code you can drop into any Laravel app. Think of it like a plugin. It might include routes, views, migrations, commands, or helpers. Packages help you:

  • Reuse your code across projects
  • Clean up your main Laravel app
  • Share useful components with others via GitHub or Packagist

🛠️ What You Need Before You Start

Before diving in, make sure you have:

  • A basic understanding of Laravel (routes, controllers, service providers)
  • Familiarity with PHP and object-oriented programming (OOP)
  • Composer installed on your machine
  • Laravel 12 installed in a fresh project

🚀 Step 1: Create a Laravel Project & Package Folder

Start by creating a fresh Laravel project (if you haven’t already):

composer create-project laravel/laravel my-project
cd my-project

Now, make a directory for your package inside your Laravel project:

mkdir -p packages/YourVendor/Calculator

Replace YourVendor with your name or company, and Calculator with your package name.


📁 Step 2: Structure Your Package

Inside packages/YourVendor/Calculator, create this structure:

src/
config/
routes/
resources/views/
database/migrations/
tests/

Each folder has a purpose:

  • src/ – main PHP code
  • config/ – configuration files
  • routes/ – web/API routes
  • resources/views/ – Blade views
  • database/migrations/ – DB migrations
  • tests/ – tests for your package

🧠 Step 3: Create the Service Provider

This is the heart of your package. Create a service provider via Artisan:

php artisan make:provider CalculatorServiceProvider

Move it to your package:

packages/YourVendor/Calculator/src/CalculatorServiceProvider.php

And update it like this:

<?php

namespace YourVendor\Calculator;

use Illuminate\Support\ServiceProvider;

class CalculatorServiceProvider extends ServiceProvider
{
    public function register()
    {
        $this->app->singleton('calculator', function () {
            return new Calculator();
        });
    }

    public function boot()
    {
        $this->loadRoutesFrom(__DIR__.'/../routes/web.php');
        $this->loadViewsFrom(__DIR__.'/../resources/views', 'calculator');
        $this->loadMigrationsFrom(__DIR__.'/../database/migrations');

        $this->publishes([
            __DIR__.'/../config/calculator.php' => config_path('calculator.php'),
        ]);
    }
}

➕ Step 4: Add the Calculator Class

Let’s build a simple calculator class to do basic operations.

// src/Calculator.php

namespace YourVendor\Calculator;

class Calculator
{
    public function add($a, $b)
    {
        return $a + $b;
    }

    public function subtract($a, $b)
    {
        return $a - $b;
    }
}

🧱 Step 5: Add a Facade (Optional but Nice)

Facades let you use your class like Calculator::add(2, 3).

// src/Facades/Calculator.php

namespace YourVendor\Calculator\Facades;

use Illuminate\Support\Facades\Facade;

class Calculator extends Facade
{
    protected static function getFacadeAccessor()
    {
        return 'calculator';
    }
}

️ Step 6: Add Configuration Support

Create your config file:

// config/calculator.php

return [
    'default_currency' => 'USD',
];

And don’t forget to publish it inside your service provider’s boot() method.


🛣️ Step 7: Add Routes and Blade View

Create your routes:

// routes/web.php

use Illuminate\Support\Facades\Route;
use YourVendor\Calculator\Facades\Calculator;

Route::get('calculate', function () {
    $result = Calculator::add(5, 3);
    return view('calculator::result', ['result' => $result]);
});

Then, make the view file:

<!-- resources/views/result.blade.php -->

<h1>Calculation Result: {{ $result }}</h1>

📦 Step 8: Tell Composer About Your Package

Update your root composer.json:

"autoload": {
    "psr-4": {
        "App\\": "app/",
        "YourVendor\\Calculator\\": "packages/YourVendor/Calculator/src/"
    }
}

Then dump the autoload:

composer dump-autoload

🧾 Step 9: Register Your Package in Laravel

Open bootstrap/providers.php and register your service provider:

return [
    // ...
    YourVendor\Calculator\CalculatorServiceProvider::class,
],

🧪 Step 10: Write Your First Test

Make sure everything works by writing a simple test:

// tests/Feature/CalculatorTest.php

namespace Tests\Feature;

use Tests\TestCase;
use YourVendor\Calculator\Calculator;

class CalculatorTest extends TestCase
{
    public function test_addition()
    {
        $calc = new Calculator();
        $this->assertEquals(8, $calc->add(5, 3));
    }
}

Run it:

php artisan test

Also, visit /calculate in the browser—you should see Calculation Result: 8.


🌍 Step 11: Make It Shareable

Want to publish your package? Follow these steps:

  1. Create a GitHub repo for your package.
  2. Add a standalone composer.json in your package:
{
    "name": "your-vendor/calculator",
    "autoload": {
        "psr-4": {
            "YourVendor\\Calculator\\": "src/"
        }
    }
}
  1. Push it to GitHub.
  2. Submit to Packagist.org so others can composer require it.

🎉 You Did It!

Congratulations! You just built your first Laravel package from scratch. This is a huge milestone as a Laravel developer.

🔁 What’s Next?

  • Write more tests using PHPUnit
  • Learn about publishing assets (JS, CSS)
  • Explore building artisan commands in your package
  • Contribute to open-source Laravel packages

💬 Final Tip: Package development helps you think modularly. Whether you're creating internal tools for your company or open-source contributions, it’s a great way to grow your skills and stand out in the Laravel community.

Happy Coding! 🚀

Tags

Comments

No comments yet. Be the first to comment!

Please log in to post a comment:

Sign in with Google

Related Posts