Create a custom helper in Laravel
Use Case Scenario:
An application requires a unique ID. The generated ID will be use as a user’s initial password when they create a user account and it will also be use as an additional URL parameter. To address that requirement, an ID generator function is created to generate the unique ID and a custom Laravel Helper so that the ID generator can be called anywhere in the application instead of writing the whole code every time that it is needed.
1. Go to app/Helpers directory within your Laravel project. If this directory doesn’t exist, create it.
2. Create a new PHP file in the app/Helpers directory. ex. MyHelpers.php
3. Create the custom function. Let’s say we want to make a function that generates a random ID string
function GenerateID($length = 15)
{
$num_and_let = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$randID = ''
for($a = 0; $a < length; $a++) {
$randID .= $num_and_let[rand(0, strlen($num_and_let) - 1)];
}
return $randID;
}
4. Add the helper file (MyHelpers.php) in the “auto-load” section. You can do this by adding an autoload entry to the composer.json file in your Laravel application.
"autoload": {
"files": [
"app/Helpers/MyHelpers.php"
]
}
5. Run the following command in your terminal to regenerate the Composer autoloader files
composer dump-autoload
6. Use the custom helper function GenerateID() anywhere in your Laravel application by calling the function
$randomID = GenerateID(15);
Watch the video in YouTube and
Support WeHelpCode by subscribing to our YouTube Channel