Creating new helper function in laravel 11

 

1. Create a Helper File

Create a new PHP file to store your helper functions. Laravel doesn't come with a dedicated helper file by default, but you can create one in the app/Helpers directory (or any directory you prefer).

Example:

bash
mkdir app/Helpers touch app/Helpers/helpers.php

2. Define Your Helper Function

Add your function(s) to the new helper file.

Example (app/Helpers/helpers.php):

php
<?php if (!function_exists('greetUser')) { function greetUser($name) { return "Hello, $name!"; } }

3. Include the Helper File

You need to include this file in the application so that Laravel can load the functions.

Option 1: Autoload via composer.json

Edit your composer.json file and add the helper file under the autoload section:

json
"autoload": { "files": [ "app/Helpers/helpers.php" ] }

After adding this, run the following command to regenerate the autoload files:

bash
composer dump-autoload

Option 2: Include in AppServiceProvider

Alternatively, you can include the helper file in the AppServiceProvider or a custom service provider.

Add the following to the boot method of App\Providers\AppServiceProvider:

php
public function boot() { require_once app_path('Helpers/helpers.php'); }

Comments

Popular posts from this blog

useCallback hook in React

Passing array from child to parent component

Enhance existing Laravel CRUD application with advanced search and filtering capabilities.