Create Custom Helper Functions in Laravel
Last updated on Jul 26, 2021
Read 441 times

This article is about custom helper functions in Laravel 8. We'll show you how to use custom helpers in Laravel 8. This article explains how to build a custom helper function in Laravel 8.
We already know that Laravel 8 has utility functions for arrays, URLs, routes, and paths. However, not all of the functions that we require are available. Perhaps some fundamental assistance functions, such as date format, might be included in our project. It is frequently required. As a result, I believe we should develop our helper function and use the same code everywhere.
So, let's make a helpers file in Laravel 8 by following the instructions below.
Now, all you have to do to add custom helper functions to your website or project directory is follow three simple steps and utilize them.
1 : Make a file called helpers.php.
Create a file called app/helpers.php
in your Laravel project and paste the following code into it:
app/helpers.php
if (!function_exists('isHttps')) {
function isHttps()
{
return !empty($_SERVER['HTTPS']) && ('on' == $_SERVER['HTTPS']);
}
}
if (!function_exists('getBaseURL')) {
function getBaseURL()
{
$root = (isHttps() ? "https://" : "http://").$_SERVER['HTTP_HOST'];
$root .= str_replace(basename($_SERVER['SCRIPT_NAME']), '', $_SERVER['SCRIPT_NAME']);
return $root;
}
}
2: In the composer.json file, add the file path.
In this stage, you must provide the location of the helpers file, so open composer.json and paste the following code into it:
composer.json
................
"autoload": {
"psr-4": {
"App\\": "app/",
"Database\\Factories\\": "database/factories/",
"Database\\Seeders\\": "database/seeders/"
},
"files": [
"app/helpers.php"
]
},
................
3: Execute the command
This is the final stage; simply execute the following command:
composer dump-autoload
Finally, you can use your custom helper methods like get the base url of your project . I'll show you how to utilize custom helper functions in the following example:
In the blade file
echo getBaseURL();
output will be:
http://www.ebusinessobserver.com
Muhammad Umer
Aug 05, 2021