DEV Community

Cover image for How to Create a Package in Laravel
Snehal Rajeev Moon
Snehal Rajeev Moon

Posted on

2

How to Create a Package in Laravel

Hello Artisan,

Laravel is one of the most popular PHP frameworks, and its modular nature allows developers to create reusable packages. A package is a self-contained bundle of reusable code that can be shared and installed across multiple Laravel projects.

In this guide, we will walk you through creating a Laravel package from scratch for user-management.

Step 1: Set Up a New Laravel Package
Before starting, make sure you have Laravel installed. You can create a Laravel package in two ways:

  • Inside an existing Laravel application - (useful for testing while developing).

  • As a standalone package - (useful for distributing to others via Packagist).

1. Create a Directory for the Package
Navigate to your Laravel project’s packages directory (if it doesn’t exist, create it):

mkdir -p packages/laravelusermanager
cd packages/laravelusermanager
Enter fullscreen mode Exit fullscreen mode

2. Initialize Composer
Run the following command inside the package directory to initialize Composer:

composer init
Enter fullscreen mode Exit fullscreen mode

3. Define the Package in composer.json
In your package’s composer.json, ensure it includes the following:

{
    "name": "laraelusermanager",
    "description": "A sample Laravel package for user management",
    "type": "library",
    "autoload": {
        "psr-4": {
            "LaravelUserManager\\LaravelUserManager\\": "src/"
        }
    },
    "require": {
        "php": ">=8.0",
        "illuminate/support": "^10.0"
    }
}
Enter fullscreen mode Exit fullscreen mode

4. Register the Package in Laravel
In your Laravel application, add your package’s namespace to composer.json in the root project:

"autoload": {
    "psr-4": {
        "LaravelUserManager\\LaravelUserManager\\": "packages/laravelusermanager/src/"
    }
}
Enter fullscreen mode Exit fullscreen mode

Run composer dump-autoload to reload the autoload files.

Step 2: Create the Package Structure

Inside packages/laravelusermanager/, create the following directories:

mkdir -p src config routes resources/views
Enter fullscreen mode Exit fullscreen mode

1. Create the Service Provider

Create a file src/PackageServiceProvider.php and define the service provider:

<?php

namespace VendorName\LaravelUserManager;

use Illuminate\Support\ServiceProvider;

class PackageServiceProvider extends ServiceProvider
{
    public function boot()
    {
        // Load routes
        $this->loadRoutesFrom(__DIR__.'/../routes/web.php');

        // Load views
        $this->loadViewsFrom(__DIR__.'/../resources/views', 'laravelusermanager');

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

    public function register()
    {
        // Merge package config
        $this->mergeConfigFrom(__DIR__.'/../config/config.php', 'laravelusermanager');
    }
}
Enter fullscreen mode Exit fullscreen mode

2. Define Routes

Create routes/web.php:

<?php

use Illuminate\Support\Facades\Route;
use LaravelUserManager\Controllers\UserController;

Route::resource('users', UserController::class);
Enter fullscreen mode Exit fullscreen mode

3. Create a Configuration File

Create config/config.php:

<?php

return [
    'setting' => 'default_value',
];
Enter fullscreen mode Exit fullscreen mode

4. Create a View

Create resources/views/users/index.blade.php:

<h1>User List</h1>
<table>
    <tr>
        <th>ID</th>
        <th>Name</th>
        <th>Email</th>
    </tr>
    @foreach ($users as $user)
        <tr>
            <td>{{ $user->id }}</td>
            <td>{{ $user->name }}</td>
            <td>{{ $user->email }}</td>
        </tr>
    @endforeach
</table>
Enter fullscreen mode Exit fullscreen mode

5. Create a Controller

Create src/Controllers/UserController.php:

<?php

namespace LaravelUserManager\LaravelUserManager\Controllers;

use Illuminate\Http\Request;
use App\Models\User;
use Illuminate\Routing\Controller;

class UserController extends Controller
{
    public function index()
    {
        $users = User::all();
        return view('laravelusermanager::users.index', compact('users'));
    }

    public function create()
    {
        return view('laravelusermanager::users.create');
    }

    public function store(Request $request)
    {
        User::create($request->all());
        return redirect()->route('users.index');
    }
}
Enter fullscreen mode Exit fullscreen mode

Step 3: Register the Package in Laravel

In config/app.php, add the service provider to the providers array:

'providers' => [
    LaravelUserManager\PackageServiceProvider::class,
];
Enter fullscreen mode Exit fullscreen mode

Step 4: Test the Package

Run php artisan serve and visit http://localhost:8000/users. You should see the list of users.

Step 5: Publishing the Package

If you want to share your package with others: Push your code to GitHub.

Submit it to Packagist by registering it in your Composer account.

To install it in other Laravel projects, use:
composer require laravelusermanager

Conclusion
Creating a Laravel package is a great way to modularize and reuse code. By following these steps, you can build and distribute your own Laravel packages efficiently!

Happy Reading!
Happy Coding!

❤️ 🦄

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay