$ cat /posts/how-to-create-custom-helper-functions-in-laravel.md

How to create custom helper functions in Laravel

drwxr-xr-x2026-01-095 min0 views
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

markdown
app/
├── Console/
├── Events/
├── Exceptions/
├── Http/
├── Jobs/
├── Listeners/
├── Providers/
├── helpers.php
└── User.php

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

php
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

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)

bash
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

php
public function index(){
    $result = uniqueId();
    dd($result);
}

Using our controller function in view (.blade files)

php
@extends('layouts.master')
  @section('content')
    <div class="title m-b-md">
      {{ uniqueId() }}
    </div>
@stop
$ echo $TAGS: #PHP #Laravel

$ cat /comments/ (0)

new_comment.sh

// Email hidden from public

>_

$ cat /comments/

// No comments found. Be the first!

[session] guest@{codershandbook}[timestamp] 2026

Navigation

Categories

Connect

Subscribe

// 2026 {Coders Handbook}. EOF.