Laravel Clean Code (1)

Ali Heydari
2 min readAug 30, 2022

--

Writing clean and readable code is one of the developer’s concerns. Senior programmers manage to do this more easily by relying on their experience as well as their studies, and novice programmers do their best while gaining experience.

In this article, we collected some tips for writing cleaner code in Laravel, and we are going to mention some general recommendations in Laravel coding for those interested. These tips are a great starting point for developing a proper understanding of good code and bad code. Note that we are listing these points in no particular order along with the sample code, and each is important in its own right.

  1. Using Form Requests

Consider using Form Requests. They are a great place to hide complex validation logic.

public function rules() {
return [
'title' => 'required|unique:posts|max:255',
'body' => 'required',
];
}

2. Using Scope Query

Instead of writing complex Where() statements, create Scope Queries with clear names.

Order::query()->completed()->get();class Order extends Model  {  
public function scopeCompleted($query) {
return $query->where('status', 'completed')
}
}

3. Method extraction from complex codes

If the method is too long or complex and it is difficult to understand exactly what is happening, then split the logic in the method into several methods.

public function handle(Request $request, Closure $next)
{
// We extracted 3 tong methods into separate methods.
$this->trackVisitor();
$this->trackCampaign();
$this->trackTrafficSource($request);
$response = $next($request); $this->analytics->log($request); return $response;
}

4. Create helper functions

If you repeat parts of the code a lot, consider whether extracting it into a helper function would make the code cleaner.

function money(int $amount, string $currency = null): Money  
{
return new Money($amount, $currency ??
config('shop.base_currency'));
}
function html2text($html = ''): string
{
return str_replace(' ', ' ', strip_tags($html));
}

5. Avoid too many parameters in functions

When you see a function with a lot of parameters, it can mean:

  • The method has too many responsibilities and should be separated.
  • Responsibilities are good, but you need to fix the long ones.

Each of the mentioned points, if used in the right place, will make us have a cleaner and more readable code. Also, fully understanding and applying them will make you a better developer. But clean coding tips are not limited to these things and we have explained more tips in the second part of this article.

--

--

No responses yet