Today I want to talk about several useful tricks, using which you can simplify the code of your Laravel project and avoid various mistakes. These are not all the things that you need to know about when you working with this framework, but only the Top 5 Laravel Best Practices that seemed to me the most important.

Validation in Request classes

Try to avoid validation in controllers. Instead, create a Request class and place it there.

Avoid:

public function store(Request $request)
{
    $request->validate([
        'title' => 'required|max:255',
        'content' => 'required'
    ]);
    /// your code here
}

Strive for:

public function store(StoreReportRequest $request)
{
    /// your code here
}
class StoreReportRequest extends FormRequest
{
    public function rules()
    {
        return [
            'title' => 'required|max:255',
            'content' => 'required'
        ];
    }
}

To quickly create a template for the Request class, you can use the artisan command: php artisan make:request StoreReportRequest

Mass assignment in Laravel

Use mass assignment when creating new instances.

Avoid:

$report = new Report;
$report->title = $request->title;
$report->content = $request->content;
// Add unit to report
$report->unit_id = $unit->id;
$report->save();

Strive for:

$unit->report()->create($request->validated());

Eager loading

By default, Eloquent queries load related models lazily. That is, they are not loaded until they are referenced in the code. Thus, in the example below, which should be avoided, 51 queries will be used to display 50 reports from the database, since each time a unit is accessed, a separate additional query will be made.

And in the example, to which we need to strive, “eager loading” was used, thus, only 2 requests will be made and all related units will be loaded at once.

Avoid:

$reports = Report::all();
foreach ($reports as $report) {
    echo $report->unit->name;
}

Strive for:

$reports = Report::with('unit')->get();
foreach ($reports as $report) {
    echo $report->unit->name;
}

No text in the code

Don’t use any text in your code. It can lead to two problems:

  • If you want to change it later, it will often be difficult to find and will have to be changed in many places where it was added;
  • If the project has several languages, then the text in the code will be rigidly set only one.

Therefore, it is better to use localization files or constants.

Avoid:

if ($reports->status === 'success') {
        //your code here
}
$message = 'Successfully created!';

Strive for:

if ($reports->status === Report::STATUS_SUCCESS) {
    //your code here
}
$message = __('messages.success');

Don’t get data directly from the .env file

Never get information directly from a .env file, as this can lead to many problems including incorrect caching. Instead, add getting information to the config file and get the data using the config method.

Avoid:

$paymentKey = env('PAYMENT_KEY');

Strive for:

// add value to config/api.php
'payment_key' => env('PAYMENT_KEY'),
// get data from config
$paymentKey = config('api.payment_key');

That concludes my list of my Top 5 Laravel Best Practices.

If the article turns out to be useful to you, write about it in the comments, and I will release the second part. Also don’t forget to subscribe to my twitter. See you later!

Share post
Twitter Facebook