9 Laravel Best Practices for Building Better Websites

By: Tricia Pearson
  |  February 28, 2024
9 Laravel Best Practices for Building Better Websites

Larval is one of the most popular PHP frameworks, created especially to help developers quickly build web applications. According to builtwith.com, more than 27.5 million websites use a PHP framework, making up 14% of worldwide websites. However, you should always adhere to the following Laravel best practices to make Laravel development a breeze and reap maximum benefits. 

9 Best Practices for Laravel Development

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. Adhere to the Coding Standards

Laravel is flexible in coding. If your variables are compatible with the composer, you’re good. Adhering to PSR-2 and PSR-4 coding standards will keep your code clean and free of confusion. 

Here’s what PSR-2 and PSR-4 coding standards mean:

  • PSR-2: Have a single style guide for your PHP code to keep a uniform format
  • PSR-4: Specify autoloading classes from the file path to ensure files autoload in your code where you want them to

GrumPHP is helpful for improving your Laravel coding standards.

3. 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.

Here’s an example:

public function newId()
{
   
....
   
$id = Str::random(24);
   
....
}

4. 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'];
}

5. Use Artisan CLI

Using Laravel’s Artisan CLI is another best approach to ace web development in Laravel. It uses the Symfony Console component that helps you make the web development process smooth. Also, the Artisan commands help in task scheduling and triggering actions if any event happens.

Here’s an example of how you can fire an Artisan command from an HTTP route:

Route::get(‘/foo’, function()
{
$exitCode = Artisan::call(‘command:name), [‘==option’ => ‘foo’]);
//
});

Below are some helpful Artisan CLI commands to speed up the overall development process:

  • php artisan config: clear and then php artisan config: cache – This command limits the IO request and makes loading faster by combining all configuration options for your application into a single file
  • php artisan route: clear and then php artisan route: cache – This command reduces the overall computation time. Don’t use it if you have closure-based routes
  • php artisan optimize – This command compiles all your views and optimizes the autoloader

6. Use Request Classes for Validation

Always carry out validation in request classes as it has options like form request (a separate request class containing validation logic). You can use other methods, but the best approach is doing this:

Do This:

public function store(CreateArticleRequest $request)
{    
    ....
}
class CreateArticleRequest extends Request
{
    public function rules(): array
    {
        return [
            'slug' => 'required',
            'title' => 'required|unique:posts|max:255',
            'body' => 'required',
            'flImage' => ['image', 'required', 'mimes:png,jpg,jpeg,gif']
        ];
    }
}

Don’t Do This:

public function store(Request $request)
{
    $request->validate([
        'slug' => 'required',
        'title' => 'required|unique:posts|max:255',
        'body' => 'required',
        'flImage' => ['image', 'required', 'mimes:png,jpg,jpeg,gif']
    ]);
}

7. Use Timeout HTTP Request 

The timeout HTTP request will help you prevent timeout errors. It is essential because Laravel times out after 30 seconds and often networks can be unreliable. Without using a timeout HTTP request, any long delays in the request will hang the application indefinitely. So, make sure you use timeouts where you need them, and long delays will only generate an error.

Here’s an example of a perfect instance:

public function makeRequest(CreateArticleRequest $request)
{
    ....
    $response = Http::timeout(120)->get(...);
    ....
}

8. Use the chunk() Function to Break Down Heavy Tasks

The chunk() function helps you become more efficient by breaking down time-consuming tasks. Hence, it’s always wise to use it. 

Here’s how you can use the chunk() function in your Laravel code:

$this->chunk(100, function ($articles) {
    foreach ($articles as $article) {
        ...
    }
});

9. Avoid Using Environment (.env) Variables Directly in Your Code

Environmental variables are a value that affects the way running processes behave in a computer. While you may be tempted to use them directly in your code, it’s best if you use the config() helper function to access them. Otherwise, external variables, like server-level or system-level environment variables, can easily override your .env file.

So, Do This:

// config/api.php
'key' => env('API_KEY'),
 
// Use the data
$apiKey = config('api.key');

And DON’T Do This:

$apiKey = env('API_KEY');

In Conclusion

A web development framework is as good as the practices you follow. Frameworks ensure you don’t make mistakes that drag you down and move your applications ahead in the right direction. Hopefully, the Laravel practices we shared above gave you a fair idea of what you should do to develop quality websites faster in Laravel. Follow these practices on your next website, and it will stand out.

Improve Your Code with Retrace APM

Stackify's APM tools are used by thousands of .NET, Java, PHP, Node.js, Python, & Ruby developers all over the world.
Explore Retrace's product features to learn more.

Learn More

Want to contribute to the Stackify blog?

If you would like to be a guest contributor to the Stackify blog please reach out to [email protected]