Create helper functions/custom classes in Laravel - helpers
Content Index
- What do we want to do?
- Step 1: Create a helper.php file in the Laravel application folder.
- 2. Register in composer.json
- Step 3: Write your function in app/Helpers/helpers.php
- Step 4: Refresh dependencies
- Step 5: Usage
- DO NOT use the env() helper function in Laravel
- The correct alternative: config()
- Advantages of using config()
- Displaying text based on the Laravel environment or mode
- Showing or hiding content based on the environment
- Options to check the environment
Helper functions are nothing more than common functions that we can call anywhere in our application. Laravel comes with a number of really useful built-in helper functions; among the most used, we have url(), route(), asset(), env(), app(), request(), env(). You can find the complete list of these here:
https://laravel.com/docs/master/helpers
But as developers, we sometimes we don't just want to detect mobile browsing, but also, need to write some functions that help eliminate repetitive code and add speed to our development. So I'll show you how to create custom helper classes and use them in Laravel projects.
In Laravel, a helper is a globally scoped function, meaning that from any component class, controller, model, view... we can access it to trigger its corresponding functionality. Helpers are not something invented by Laravel; they exist in many other frameworks. Helpers have gained more and more ground in the latest versions of Laravel, creating helper functions for other processes that were previously Facades (which are considered anti-patterns). Therefore, we can use the system's own helpers or create our own, as we will show in this post.
What do we want to do?
In this application, I want to log all activities as notifications in a table. When they log in, when they comment, when they visit a page, when they like, post, follow, and any action we can think of.
Helper functions or helpers are functionalities that we can create throughout the app that are general purpose; they are generally NOT linked to a business process or logic, but are functions of a more general purpose such as performing some process with texts, numbers, images... and in Laravel, of course, we can create this type of processes or helper functions: for that, we have to follow 5 simple steps.
Step 1: Create a helper.php file in the Laravel application folder.
Helper.php files are often found in the following places:
- app/Http/helpers.php
- app/Helpers/helpers.php
- app/helpers.php
For this lesson, we will use app/Helpers/helpers.php.
<?php
namespace App\Helpers;
class Helper{
public static function hello(string $hello){
return "Hola $hello";
}
}There, we define all our functions, we can even create more files with helper functions in case you want to have some order in your functions; it is important to mention that you can create as many helper files in this folder (or other folders or subfolders) for your application, therefore, you are not limited to a single file.
2. Register in composer.json
Once your helper file(s) with your functions have been created, the next thing we have to do is register it to be able to use it globally in the project; for this, we have to register it in a rule called autoload, under the files key, put the reference to your helpers files:
"autoload": {
"psr-4": {
"App\\": "app/"
},
"files" : ["app/Helpers/Helper.php"],
"classmap": [
"database/seeds",
"database/factories"
]
},The same here, for each helper file you have, you register it in the files array.
Step 3: Write your function in app/Helpers/helpers.php
Helper functions are usually functionalities within the application that are not part of the business logic and that we want to use throughout the app
<?php
namespace App\Helpers;
use App\Models\Notification;
class NotifyClass
{
private $data = null;
public function __construct($data)
{
$this->data = $data;
}
public function make(): bool
{
$notify = Notification::create([
'user_id' => $this->data['user_id'],
'type' => $this->data['type'],
'created_at' => now()
]);
if ($notify)
return true;
else
return false;
}
}
<?php
namespace App\Helpers;
class Helper{
public static function hello(string $hello){
return "Hola $hello";
}
}Step 4: Refresh dependencies
With everything correctly registered, the next thing we have to do is execute a composer command so that, just like with any other Laravel package, it indexes it in our composer startup file:
$ composer dump-autoloadWith this, we can now use our functions anywhere in our project, as we see in the video attached to our post.
Step 5: Usage
The next thing we must do is learn how to make use of this helper class.
In your controllers, you only need to add the namespace and call it.
use App\Helpers\NotifyClass;
//after following a user,
$data = [
'user' => Auth::user()->id,
'type' => 'follow'
]
(new NotifyClass($data))->make();
//after liking a post,
$data = [
'user' => Auth::user()->id,
'type' => 'like'
]
(new NotifyClass($data))->make();
//after ordering a product,
$data = [
'user' => Auth::user()->id,
'type' => 'order'
]
(new NotifyClass($data))->make();
(new NotifyClass($data))->make();There are many things you can do.
Now, we can call the notification helper class and log a user's action in the database. We can add an "action_id" or "notifiable_id" that we can use to save the ID that receives the user's action. For example, a user orders a product, action_id will be the product identifier, and the type will be "order".
use App\Helpers\NotifyClass;
//after ordering a product,
$data = [
'user' => Auth::user()->id,
'type' => 'order'
'action_id' => 784 //product id
]
(new NotifyClass($data))->make();It's all about what you want to do.
There are several ways to use helper classes in Laravel. You can make static functions for basic use and as anything you want to use multiple times in a generic way.
There are methods that require you to autoload these functions and everything, but here we simplify it. Try it out and use it in your next project.
https://medium.com/@prevailexcellent/create-custom-helper-functions-classes-in-laravel-8-9-and-use-them-bb4432ea3511
DO NOT use the env() helper function in Laravel
There are many helper functions we can use in Laravel, among the best known is env().
It is not recommended to use the env() function directly in your controllers or development without clearly defining its use first. Here's why:
- Nature of environment variables
The variables that env() references come from your Laravel project's .env file. This file centralizes multiple configurations in one place, but it does not guarantee that all variables are defined in production. If you use env() directly and a variable is missing, you can generate unexpected errors. - Risk of inconsistencies
It is possible that you forget to define a variable in a specific environment, causing your application to rely on values that do not exist outside the local environment. This can cause failures in production. - Maintenance difficulty
By using env() in various places in your application, it becomes more difficult to change or manage configuration values, since the code directly depends on the .env file.
The correct alternative: config()
Instead of using env() directly, define your values at the configuration level and access them using the config() helper function.
For example:
Create or modify a configuration file, such as config/services.php:
return [
'paypal' => [
'client_id' => env('PAYPAL_CLIENT_ID', ''),
'secret' => env('PAYPAL_SECRET', ''),
],
'dropbox' => [
'token' => env('DROPBOX_TOKEN', ''),
],
];Access these values from your application with config():
$paypalClientId = config('services.paypal.client_id');
$dropboxToken = config('services.dropbox.token');Advantages of using config()
You avoid depending directly on the .env file.
You ensure that all configuration values are centralized and consistent across all environments.
You facilitate the maintenance and scalability of your application.
You allow defining default values to prevent errors if a variable is undefined in production.
Displaying text based on the Laravel environment or mode
Laravel has three types of environments: local, production, and testing.
- Local: Used for application development.
- Production: Used to host the application in a live environment.
- Testing: Used to run automated tests on the application.
Each environment can have its own configuration, located in the project's config folder. This allows setting different values for each environment, offering flexibility in configuration. For example, different credentials can be defined for the database in development and production.
In general, the use of environments in Laravel improves control and flexibility over the application's configuration, which in turn can increase software quality and development team efficiency.
Showing or hiding content based on the environment
A common task in development is to show or hide text or HTML elements, or even start or stop processes, depending on the environment we are in. This can be easily done by checking the status of our project's environment.
Options to check the environment
The best way to do this is by using the project's configuration file, as it is clean and simple. It is also possible to directly ask Laravel what the current environment is.
For example:
Usando config('app.env')
@if (config('app.env') === 'production')
Text in Production
@endif
Usando app()->environment()
@if (app()->environment() === 'production')
Text in Production
@endifOr even passing the environment name directly:
@if (app()->environment('production'))
Texto en Producción
@endifWith this, you now know how to display content based on the environment in Laravel, leveraging the configuration of each environment for your application.
The next step is to learn how to use custom exceptions in Laravel for error handling.
I agree to receive announcements of interest about this Blog.
Helper functions are simply common functions that we can call anywhere in our application; in this post I'll show you how to create custom helper classes and use them in Laravel projects.