In Laravel, a helper function is a PHP function that you can use globally in your application. You can create a helper function by defining it in a separate PHP file and then autoloading it or by defining it in a service provider.
Here is an example of how you can create a helper function in Laravel:
- Create a new PHP file in the
app/Helpers
directory (or any other directory of your choice). Let’s call ithelpers.php
. - In the
helpers.php
file, define your helper function. For example:
<?php
if (! function_exists('hello')) {
function hello()
{
return 'Hello, World!';
}
}
- Autoload the helper file by adding the following line to the
composer.json
file in the root of your Laravel project:
"autoload": {
"files": [
"app/Helpers/helpers.php"
]
}
- Run the following command to update the autoloader:
composer dump-autoload
- You can now use the
hello()
function anywhere in your application by calling it like this:
echo hello();
Alternatively,
you can define your helper function in a service provider and register it as a singleton. To do this, follow these steps:
- Create a new service provider by running the following Artisan command:
echo hello();
- In the
app/Providers/HelperServiceProvider.php
file, define your helper function in theboot()
method. For example:
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class HelperServiceProvider extends ServiceProvider
{
public function boot()
{
if (! function_exists('hello')) {
function hello()
{
return 'Hello, World!';
}
}
}
}
- Register the service provider in the
config/app.php
file by adding it to theproviders
array:
'providers' => [
// Other service providers...
App\Providers\HelperServiceProvider::class,
],
- You can now use the
hello()
function anywhere in your application by calling it like this:
echo hello();