Spread the love

Sometimes in our application we want some our custom own helper functions to use in our application, Laravel has so many helpers functions to work with strings, URL, email, array, debugging etc. so in this article i will show you to use custom helper functions in our Laravel application.

Let’s begin the tutorial of Create Custom Own Helper Functions step by step

Step 1 : Create a helper file

First step is create a helper file in app folder or we can create a folder in app folder then we can create multiple files in that folder. in this example i am going to create a file in app/helpers.php

<?php 

function myTestFunction(){

    return "this is a simple test function from readerstacks.com";

}

Step 2 : Register helper in composer.json

To auto load our helpers.php we need to register it in our composer.json file. Generally in core PHP we include our new file and then we can directly use that in any file but now we have much better way to include it in our application using the composer as below.

"autoload": {
    "files": [
        "app/helpers.php"
    ],
    "classmap": [
        "database/seeds",
        "database/factories"
    ],
    "psr-4": {
        "App\\": "app/"
    }
},

As you can se we have added

 "files": [
        "app/helpers.php"
    ],

in composer.json, composer has a files key which accepts array and where you can define your custom files.

then run the below command in terminal to update the autoloader

composer dump-autoload

Step 3 : Create Routes

Now, Create a route to check our implementation on controller or route itself using anonymous function.

<?php

use Illuminate\Support\Facades\Route;
 
Route::get('/helper',function(){
   return myTestFunction();
}); 

Or in controller

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\ArticleController;

 
Route::get('/helper',[ArticleController::class, 'helper']); 

Create a controller in app\Http\Controllers\ArticleController and method helper

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;

class ArticleController extends Controller
{
    public function helperTest(Request $request)
    {
        return myTestFunction();
    }
}
?>

Step 4: Example to use in view

Same as controller and route we can use the custom helpers in view blade file, so create a file in resources/views folder

 <div class="row jsc">
           <h2>
           {{myTestFunction()}}
          </h2>
 </div>

and in controller or route

<?php

use Illuminate\Support\Facades\Route;
 
Route::get('/helper',function(){
   return view("helper");
}); 
Custom Laravel helper example

Also Read : Create custom class or library class in Laravel 8

Leave a Reply