Laravel 6.2 Custom Helper Tutorial with Example
In this article, we are going to learn how to make a custom helper in Laravel 6.2. We can define many custom functions in the helper and we can use the functions anywhere we want.
Let’s follow these steps to create a custom helper:
Table of Contents
Step 1 : Create helpers.php File
Navigate to app
folder and create a file called “helpers.php‘. We are going to create a currency convert function in the custom helper. Paste the below code in the helper.
<?php
function convertCurrency($amount,$from_currency,$to_currency){
$apiKey = 'your-api-key-here';
$from_Currency = urlencode($from_currency);
$to_Currency = urlencode($to_currency);
$query = "{$from_Currency}_{$to_Currency}";
// change to the free URL if you're using the free version
$json = file_get_contents("https://api.currconv.com/api/v7/convert?q={$query}&compact=ultra&apiKey={$apiKey}");
$obj = json_decode($json, true);
$val = floatval($obj["$query"]);
$total = $val * $amount;
return number_format($total, 2, '.', '');
}
Step 2 : Define Helper in composer.json
Open the composer.json file and in the autoload section we need to define the location of helpers.php. Let’s define:
"autoload": {
"psr-4": {
"App\\": "app/"
},
"classmap": [
"database/seeds",
"database/factories"
],
"files": [
"app/helpers.php"
]
},
After adding the helpers.php, run this command to load the file globally in our project:
composer dump-autoload
Step 3 : Use in Controller
We have created the custom helper. Let’s call from the controller.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Response;
class TestController extends Controller
{
public function index()
{
$converted_amount = convertCurrency(10, 'USD', 'GBP');
echo $converted_amount;
}
}
Step 4 : Use in Blade File
As the controller, we can also call helper functions in the view blade file. Here’s an example:
@extends('layouts.app')
@section('content')
@php
$converted_amount = convertCurrency(10, 'USD', 'GBP');
echo $converted_amount;
@endphp
@endsection
We have created and tested the custom helper. Thanks for reading. ?Md Obydullah
Software Engineer | Ethical Hacker & Cybersecurity...
Md Obydullah is a software engineer and full stack developer specialist at Laravel, Django, Vue.js, Node.js, Android, Linux Server, and Ethichal Hacking.