Create helper functions/custom classes in Laravel - helpers
Content Index
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(). You can find the complete list of these here:
https://laravel.com/docs/master/helpers
But as developers, we sometimes 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
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.