A custom helper function is a user-defined function in Laravel. Which is globally accessible throughout the application. These functions are not specific to any class or model. But serve as utility methods that can be used in various parts of the application without the need to repeat the same code. Custom helper functions are commonly used to encapsulate commonly used functionality. Or you can say it provides shorthand methods for repetitive tasks. By creating custom helpers, you can enhance code reusability and make your codebase more organized and maintainable. Custom helpers can be a convenient way to centralize utility methods or operations that don’t necessarily belong to a specific class or model. In this post, we will see, how you can create a custom helper function in Laravel 10.
Prerequisites
We are going to implement this functionality in Laravel 10. But, it is not necessary to implement this only in Laravel 10. You can use this with earlier versions of Laravel as well.
But, if you are working with Laravel 10, then you must have the below tools.
- PHP >=8.1
- Composer
- Apache/Nginx Server
- VS Code Editor (Optional)
- MySQL (version > 5)
Now, let’s continue with the example of creating the custom helper function in Laravel 10.
Step 1: Project Setup For a Custom Helper Function in Laravel 10
You can create a new project set up in Laravel 10 using the below command.
composer create-project --prefer-dist laravel/laravel demo-app
After the project setup, let’s quickly configure the database.
Get the Last Inserted Id in Laravel 10 Using Different Methods
Step 2: Create and Configure a Database
In the second setup, you need to create a database. Then come up inside the project folder and add the DB credentials as shown below.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE={{ DATABASE_NAME }}
DB_USERNAME={{ DATABASE_USERNAME }}
DB_PASSWORD={{ DATABASE_PASSWORD }}
Now, let’s move to the third step.
Step 3: Create a Helper Folder in Project Directory
Next, you need to create a folder named Helpers in the app folder. So, the directory structure will look like this.
Now, inside this Helpers folder, create a file name CustomHelper.php. After creating the file, you can create any custom helper function which you want to use it globally in your project for the re-usable purpose.
Take a look at the below snippet.
<?php
/**
* Function : Get Name from Name Array
* @param mixed $string
* @return array
*/
if (!function_exists('getName') ) {
function getName($name): array {
$nameResults = [];
$name = explode(' ', $name);
if (count($name) > 0) {
$nameResults = [
'firstName' => $name[0],
'middleName' => $name[1] ?? null,
'lastName' => $name[2] ?? null,
];
}
return $nameResults;
}
}
Here, in the above helper function, I have taken a name (string) as an input parameter. Then from this name, I have extracted the first name, middle name, and last name respectively.
So, I can use this function anywhere in the project as per the need.
Auth Scaffolding Using Jetstream with Intertia Js in Laravel 10
Step 4: Autoload the Helper File
In order to call the created custom helper function, you will have to load the helper file. So, you can load the helper file in composer.json available in the root of the project folder.
In composer.json, look at the autoload object. Then inside this, add the custom helper file in the files array as shown below.
"autoload": {
"psr-4": {
"App\\": "app/",
"Database\\Factories\\": "database/factories/",
"Database\\Seeders\\": "database/seeders/"
},
"files" : [
"app/Helpers/CustomHelper.php"
]
},
After adding this custom helper file, the composer.json file will look like this.
But, it is not finished yet. We added the custom helper file in the composer.json file. Hence, this required to be loaded the first time.
Step 5: Dump the Autoload Files in Laravel
After updating the composer.json
file, run the following command in your terminal to update the autoloader. So, you can call the helper functions directly without any object or alias.
composer dump-autoload
You can call the helper function directly by the function name in any controller. Take a look at the below example.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class UserController extends Controller
{
/**
* Function : Save User Data
* @param request
* @return response
*/
public function store(Request $request)
{
$nameArray = getName($request->name);
$user = User::create([
'first_name' => $nameArray['firstName'],
'middle_name' => $nameArray['middleName'],
'last_name' => $nameArray['lastName'],
]);
dd($user);
}
}
Run the application the see the result. You will have to pass the form request with the required parameters in order to get the name attributes.
That’s it for this post.
Leave a Reply