Dev Notes

Various Cheat Sheets and Resources by David Egan/Carawebs.

Managing Dependencies in a Laravel Package

Laravel, PHP
David Egan

When developing a custom Laravel package, you may need to require a separate package to provide functionality.

Composer makes it easy to include packages as a dependency. This is a good thing as it makes code more maintainable and means to don’t have to re-invent the wheel.

You also need to bind the third-party package to the Laravel app - you shouldn’t do this manually, as it would make using your package unecessarily complicated. Fortunately, Laravel makes it easy for you to register packages from within your custom package’s service provider class.

Use Composer to Bundle Dependencies

In this example, we’ll add the “illuminate/support” and “laravelcollective/html” packages. In your custom package composer.json:

    "require": {
        "illuminate/support": "5.4.*",

When you run composer update at the app level, Composer is smart enough to connect the dots and add the required packages to the app vendor directory.

Register Services

Within the boot() method of the custom packages service provider, you can register (bind) the “laravelcollective/html” service provider. You can also load up an alias for the package:


namespace Carawebs\Blog;

use Illuminate\Foundation\AliasLoader;
use Illuminate\Support\ServiceProvider;
use Collective\Html\HtmlServiceProvider;

 * Bind to the Laravel service container.
 * This class should be included in the Laravel app's
 * `config/app.php` 'providers' array.
class BlogProvider extends ServiceProvider
    * Bootstrap the application services.
    * @return void
    public function boot()
        // Register the HtmlServiceProvider class - like you'd generally do in the
        // `config/app.php` 'providers' array.
        $loader = AliasLoader::getInstance();
        $loader->alias('Form', '\Collective\Html\FormFacade');

        // Unrelated
        $this->loadViewsFrom(__DIR__.'/views', 'blog');

You could simplify the alias loading by passing in an array of alias => classname values to the getInstance() method:

// ...

This method acceps an array and merges this with the registered aliases.


comments powered by Disqus