Laravel has variety of global “helper” functions. We are free to use them in our own applications like app_path, ucfirst, auth, env etc. We can also define our own set of helper functions for Laravel applications and PHP packages. And we can use composer to import them. Also we can use them directly without import. Here we are Creating Own PHP Helpers in a Laravel Project.
Creating a Helpers file in a Laravel App
First create a file in app/Helpers/Helper.php
Autoloading Helper File in Laravel
Open composer.json file and add file path in files key as shown below.
"autoload": {
"files": [
"app/Helpers/Helper.php"
],
"classmap": [
"database/seeds",
"database/factories"
],
"psr-4": {
"App\\": "app/"
}
},
Once you add a new path to the files array, you need to dump the autoloader:
composer dump-autoload
Defining Helper Functions in Laravel
Now, you can create your own helper functions as shown below.
if (! function_exists('myCustomFunc')) {
function myCustomFunc($default = null) {
// ...
}
}
If you are unable to run composer commands. Then you should try this method.
Open your helper file app/Helpers/Helper.php. Create a class And create static functions as shown below.
<?php
namespace App\Helpers;
class Helper
{
public static function myCustomFunc()
{
}
}
Now, Creating Own PHP Helpers in a Laravel Project and use functions like this \App\Helpers\Helper::myCustomFunc().
Recommended
How to Create Multiple Parameters Dynamic Routes in Laravel
Laravel 8 Multiple Database and Resource Routes with Controllers
Optimize Database Queries in Laravel
Read For more Tutorials about Laravel
If you like this, share this.