9 Laravel Best Practices for Building Better Websites

  1. Always Use the Latest Version

Laravel becomes more secure and faster with each upgrade. By using the latest Laravel version, you can build more functional and secure websites. For example, Laravel 9.x, the newest release of Laravel released in February 2022, offers the following features:

Anonymous class migrations are the default behavior, so multiple migrations with the same class name will no longer create problems when trying to recreate the database from the beginning

A refreshed ignition error page is included as a default. A new query builder interface for type hinting, refactoring, and static analysis is included and is quite helpful for developers. The route list design has been overhauled for improved ease of use and functionality. That’s why it’s best to upgrade to the latest Laravel version. If you haven’t done it yet, now is the time!

2. Use Helper Functions

Some developers try to reinvent the wheel by creating their PHP helpers. It is an ambitious practice, but unsafe and potentially task-heavy. An alternative is to use the helper methods provided in Illuminate/Support/Str. They are easy, and you can call them anywhere.

Ex:-

   public function newId()

      {

        

      ....

        

      $id = Str::random(24);

        

      ....

      }
  1. Follow the Single Responsibility Principle

The single responsibility principle ensures that a class and method have only one responsibility at a time. This principle makes software implementation easy and ensures no conflict happens during changes in the future. Here’s an example of how to follow the single responsibility principle in your code:

   public function getTransactionAttribute(): bool

      {

          return $this->isVerified() ? $this->getReference() : $this->getPaymentLink();

      }




      public function isVerified(): bool

      {

          return $this->transaction && ($transaction->type == 'withdrawal') && $this->transaction->isVerified();

      }




      public function getReference(): string

      {

          return ['reference'=>$this->transaction->reference, 'status'=>'verified'];

      }




      public function getPaymentLink(): string

      {

          return ['link'=>$this->transaction->paymentLink, 'status'=>'not verified'];

      }


  1. Use SonarLint For Removing Unwanted Code Complexity

Sonar static analysis helps you build and maintain high-quality PHP code. Covering popular build systems, standards, and versions, Sonar elevates your coding game while keeping dangerous vulnerabilities at bay.

Sonar helps you write clean code

  1. Follow Laravel naming conventions

 

What                                  How                                              Good                                             Bad

 

  Controller                     singular                              ArticleController                        ArticlesController

 

  Route                           plural                                     articles/1                                      article/1

 

  Route name              snake_case                 users.show_active                        users.show-active,

with dot                                   show-active-users                         notation

 

Model                      singular                                     User                                              Users

 

  1. Use shorter and more readable syntax where possible

  Bad:

      $request->session()->get('cart');

      $request->input('name');

  Good:

      session('cart');

      $request->name;

 

  1. Validation

Move validation from controllers to Request classes.

    Bad:

      public function store(Request $request)

      {

          $request->validate([

              'title' => 'required|unique:posts|max:255',

              'body' => 'required',

              'publish_at' => 'nullable|date',

          ]);




          ...

      }

      Good:

      public function store(PostRequest $request)

      {

          ...

      }




      class PostRequest extends Request

      {

          public function rules(): array

          {

              return [

                  'title' => 'required|unique:posts|max:255',

                  'body' => 'required',

                  'publish_at' => 'nullable|date',

              ];

          }

      }


  1. Chunk data for data-heavy tasks

  Bad:

      $users = $this->get();




      foreach ($users as $user) {

          ...

      }

   Good:

      $this->chunk(500, function ($users) {

          foreach ($users as $user) {

              ...

          }

      });
  1. Other good practices

Avoid using patterns and tools that are alien to Laravel and similar frameworks (i.e. RoR, Django). If you like the Symfony (or Spring) approach for building apps, it’s a good idea to use these frameworks instead.

– Never put any logic in route files.

– Minimize usage of vanilla PHP in Blade templates.

– Use in-memory DB for testing.

– Do not override standard framework features to avoid problems related to updating the framework version and many other issues.

– Use modern PHP syntax where possible, but don’t forget about readability.

– Avoid using View Composers and similar tools unless you really know what you’re doing. In most cases, there is a better way to solve the problem.

Leave a Reply