Laravel Code Tips

Make your Laravel code cleaner, faster, and safer.

๐Ÿ”ฅ Use strict comparison

Use strict comparison

ALWAYS use strict comparison (=== and !==). If needed, cast things go the correct type before comparing. Better than weird == results

Also consider enabling strict types in your code. This will prevent passing variables of wrong data types to functions https://t.co/C0is2rghbs

๐Ÿ”ฅ It's about the *micro*

Using some "macro" philosophy for structuring your code, like hexagonal architecture or DDD won't save you.

A clean codebase is the result of constant good decisions at the micro level.

๐Ÿ”ฅ Use events

Use events

Consider offloading some logic from controllers to events. For example, when creating models.

The benefit is that creating these models will work the same everywhere (controllers, jobs, ...) and the controller has one less worry about the details of the DB schema https://t.co/6zJaMPScBk

๐Ÿ”ฅ Create single-use Blade includes

Similar to single-use traits.

This tactic is great when you have a very long template and you want to make it more manageable.

There's nothing wrong with @including headers and footers in layouts, or things like complex forms in page views.

๐Ÿ”ฅ Consider using form requests

Consider using form requests

They're a great place to hide complex validation logic.

But beware of exactly that โ€” hiding things. When your validation logic is simple, there's nothing wrong with doing it in the controller. Moving it to a form request makes it less explicit https://t.co/RwzDxANxXj

๐Ÿ”ฅ Create single-use traits

Create single-use traits

Adding methods to classes where they belong is cleaner than creating action classes for everything, but it can make the classes grow big

Consider using traits. They're meant primarily for code reuse, but there's nothing wrong with single-use traits https://t.co/dWWLNWuOoS

๐Ÿ”ฅ Avoid helper *classes*

Avoid helper *classes*

Sometimes people put helpers into a class.

Beware, it can get messy. This is a class with only static methods used as helper functions. It's usually better to put these methods into classes with related logic or just keep them as global functions. https://t.co/iIcyReIW9N

๐Ÿ”ฅ Context matters

Context matters

Above I said that moving business logic to action/service classes is good. But context matters

Here's code design advice from a popular "Laravel best practices" repo. There's absolutely no reason to put a 3-line check into a class. That's just overengineered https://t.co/zOtKmaVtMu

๐Ÿ”ฅ Don't use abbreviations

Don't use abbreviations

Don't think that long variable/method names are wrong. They're not. They're expressive.

Better to call a longer method than a short one and check the docblock to understand what it does

Same with variables. Don't use nonsense 3-letters abbreviations https://t.co/a23I1L7TtW