craete-custom-helper-funcation-in-laravel

How to create custom helper functions in Laravel

Laravel already provides many built-in functions like asset , csrf_token , view , with and many more, so we can use this function in the whole Laravel project, similarly you can create your own helper functions in Laravel to save your time, avoid duplication of code and also avoid referencing same class/file at all places.

In this example, We will create one helper file and inside that we will create one function to generate random id based on our own logic, similarly you can add many functions as you like.

let’s create helpers file in laravel just follow few step

1. Crate helpers.php File

In this step, we will create app/helpers.php file in laravel, you can place this file anywhere you want based on your structure preference and can name it however you like

We have created helpers.php file inside app directory

After creating helpers.php file put the following sample code in these file

if (!function_exists('uniqueId')) {
    function uniqueId() {
        $random = rand(100000,999999);
        return 'sel_'.$random;
    }
}

2.  Add File Path In composer.json File

Now we have to add the path of the helpers file in our composer.json file so that file is auto loaded in our project and we don’t need to reference it manually in our project. Add file path in files section in autoload, like shown below 

composer.json

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

        ]
},

3. Run below Command

Now that we have changed our composer.json file, We need to run following code to regenerate autoload class file  (autoload_classmap.php)

composer dump-autoload

And that’s it, Now you can use your helper function anywhere in your project let it be in controller or view.

  • Using helper function in controller
public function index(){
    $result = uniqueId();
    dd($result);
}
  • Using our controller function in view (.blade files)
@extends('layouts.master')
  @section('content')
    <div class="title m-b-md">
      {{ uniqueId() }}
    </div>
@stop
0 0 votes
Article Rating
guest
0 Comments
Inline Feedbacks
View all comments