Introducing: Larastrap

Introducing: Larastrap
Photo by Jan Huber / Unsplash

At least one year ago I realized that my main open source project (GASdotto: a management application for Purchasing Groups built with Laravel) was stuck on Bootstrap 3, while Bootstrap 4 was been around for a while and Bootstrap 5 was already been announced.

So I wanted to upgrade the platform. Which involves dozens of Blade templates. Including a lot of reusable internal "widgets": small templates wrapping specific HTML elements (the text input, the select input, or more specialized components) whose behaviour is provided by a set of inline parameters, to permit me to reuse the same elements across the whole codebase and keep some consistency.

The initial purpose was to adopt one of the many existing Bootstrap components collection for Laravel and wrap them with some customization. But none matched my expectations: none involved some abstraction for obvious hierarchies (form/field/input), most had tons of parameters to explicitely pass to each element (producing extremely verbose template code), and then none was approaching Bootstrap 5 nor the native Blade components subsystem introduced in Laravel 7.

Then, the idea: given that I had to rewrite lots of code, why not also do the job to extract my utility widgets in a dedicated library to be used also in other projects? This has been the inception of Larastrap.

Larastrap is described as "Opinionated Bootstrap 5 components for Laravel". And I have to admit it is really opinionated. The project evolved within many iterations, and is now a set of "x-components" with an essential peculiarity: are completely parametrized.

Each component is described by lots of parameters, which can be altered in at least four levels:

  • the defaults, carved into the code
  • the basic configurations, listed in the config/larastrap.php file and editable once by the implementor
  • the inline parameters inherited from parent containers to children
  • inline parameters for each component

The sum of them provide the final setup to actually render the component.

The killer feature of Larastrap, hovewer, is the ability to define once (in the configuration file) your own presets of parameters and use them as native components. Plus, a callback function attachable to every component type for dynamic parameters elaboration with some business logic. This permit the implementor to create his own components, ever complex ones, with a few lines of code, and reuse them across the whole platform (or even in different projects).

The Larastrap website has a page for "recipes", which includes simple (and not-that-simple) examples of this kind of custom elements: the few listed right now have been directly took from my own experience in GASdotto, but many more can be defined. And shared.

I hope this can be useful for other Laravel developers with a preference for Bootstrap, to help them having more compact and easily maintenable templates.