Fahmi Fayyadh Alfarizy

Tech Lead

Scrum Master

Freelancer

0

No products in the cart.

Fahmi Fayyadh Alfarizy
Fahmi Fayyadh Alfarizy
Fahmi Fayyadh Alfarizy
Fahmi Fayyadh Alfarizy

Tech Lead

Scrum Master

Freelancer

Blog Post

How to Create a Helper in Laravel

December 7, 2023 Laravel, Programming
How to Create a Helper in Laravel

Introduction

Laravel helpers are a great way to encapsulate reusable code and make your code more concise and readable. Helpers can be used to perform common tasks, such as formatting dates, generating random numbers, or converting between different data types.

In this tutorial, we will show you how to create a helper in Laravel. We will create a helper that formats a date in a specific format.

Creating a Helper

To create a helper in Laravel, we need to create a new file in the app/Helpers directory. The helper’s filename should be the helper’s name, followed by the .php extension.

For example, to create a helper named date_helper, we would create a new file named date_helper.php.

The helper file should contain the following code

<?php namespace App\Helpers;  use Carbon\Carbon;  classDateHelper { publicstaticfunctionformatDate($date,$format) { returnCarbon::parse($date)->format($format); } }


This code defines a helper class named DateHelper. The class contains a single method named formatDate(). The formatDate() method takes two arguments: the date to format and the format string.

To use the helper, we can require the app/Helpers directory in our application. We can then use the helper class as follows:

use App\Helpers\DateHelper;  $date='2023-08-02';  $formatted_date=DateHelper::formatDate($date,'Y-m-d');  echo$formatted_date;// 2023-08-02

This code will output the date in the Y-m-d format.

Additional Features

We can also add additional features to our helper. For example, we could add a method to format a date in a different time zone.

To do this, we would add a new method to the DateHelper class. For example, we could add the following method:

publicstaticfunctionformatDateInTimeZone($date,$timezone,$format) { returnCarbon::parse($date,$timezone)->format($format); }

This code defines a method named formatDateInTimeZone(). The formatDateInTimeZone() method takes three arguments: the date to format, the time zone, and the format string.

Use the helper, we could use as follows:

use App\Helpers\DateHelper;  $date='2023-08-02'; $timezone='UTC+7';  $formatted_date=DateHelper::formatDateInTimeZone($date,$timezone,'Y-m-d');  echo$formatted_date;// 2023-08-02T07:00:00+07:00

This code will output the date in the Y-m-d format, in the UTC+7 time zone.

Conclusion

Laravel helpers are a great way to encapsulate reusable code and make your code more concise and readable. You can learn how to create a helper in Laravel by following the steps in this tutorial.

Write a comment