...
Laravel, Tutorials

Add custom helper function in laravel

13 March 2019

Laravel custom Helper class

Laravel has a lot of cool and useful helper functions built into it. However sometimes we need to create custom helper functions, and we need them all over our application. Here I’ll explain how to create a Helper class to generate custom helper functions in Laravel.

There are many helper functions defined in the laravel core, you can define your own helper functions in laravel to avoid repeating the same code. It ensures better maintainability of your application.

To start with create a directory in your app directory called Libraries and inside create a new PHP file called Helpers.php. This will be where we build our helper class.

Define Helper class

app/Helpers/Helper.php

namespace App\Helpers;
class Helper{
    public static function test_helper(){
        return "Test";
    }
}

config/app.php

'aliases' => [
    /*Defaults...*/
    'Helper' => App\Helpers\Helper::class, 
],

Use Helper class

app/Http/Controllers/MyController.php

<?php
     namespace App\Http\Controllers;

     use App\Http\Controllers\Controller;
     use Helper; // Important
     class MyController extends Controller{
           public function index(){
                 return Helper::test_helper();
          }
     }
?>

Thats all it takes to create custom helper functions in Laravel. These can then be used anywhere in your app.

Leave a Comments