How to minimise CRUD front-end code duplication in Laravel 5.4 / Twig

CRUD (Create/Read/Update/Delete) is something that developers do quite a bit of. Frameworks can help with this, but there’s still a fair amount of code you’ll need to write for every CRUD screen you put together.

One particular area is the difference between Create and Update. For many of the projects I’ve worked on, Create and Update are often very similar. They aren’t identical, but if there’s enough overlap between them, you can minimise duplicate code with the following setup.

Continue reading “How to minimise CRUD front-end code duplication in Laravel 5.4 / Twig”


How to display errors in Laravel 5.4 with Twig / TwigBridge

As Laravel ships with Blade, the Laravel manual gives templating examples in Blade.

For displaying basic variables in a Twig template, it’s pretty simple:

{{ title }}

However, it takes slightly more effort to display form validation errors.

Continue reading “How to display errors in Laravel 5.4 with Twig / TwigBridge”

Setting up Twig in Laravel

Re-posted from my old blog

This week, I have been mostly trying… Laravel.

Trying a new PHP framework raises a few questions. What coding style does it use? How do you build models? What do templates look like?

When trying Laravel for the first time, I wasn’t keen on the Blade templating engine. So I decided to look for how to integrate Twig. One quick Google search later, and I found TwigBridge by Rob Crowe.

Following the instructions was simple enough. However, I think there was one thing missing. What do you name your template files so Twig can find them?

How to name Twig templates in Laravel

In Laravel, a Blade template for the “users” route would be called: users.blade.php

After a bit of experimenting, I found that the equivalent Twig template would be called: users.twig

This works out nicely in PhpStorm, as suddenly the file icon changed from a PHP file to a bit of green grass (maybe it looks better than a twig). And the code completion works. That’s much better than the last project I set up with Twig, which is on Zend Framework v1 and the files are named index.html.

Don’t forget to rename your base template to base.twig or similar. The Blade equivalent I created in the QuickStart guide was called layout.blade.php.

Comparing Blade and Twig templates

So, just for completeness, here’s a sample Blade template:

 @foreach($users as $user)
 <p>{{ $user->name }}</p>

And here’s a Twig template:

{% extends "base.twig" %}
{% block content %}
{% for User in UserList %}
<p>{{ }}</p>
{% endfor %}
{% endblock content %}

So far, I’m liking Laravel, but I’m much happier with Twig than Blade.