Laravel 11 Create Custom Helper Functions Tutorial

Laravel 11 custom helper fuctions; Throguh this tutorial, i am going to show you how to create a custom helper in Laravel 11 apps. And how to call the helper function in Laravel 11 on blade view, controller, and model files.

How to Create Helper and Function in Laravel 11

Use the below given steps to create and use custom helper functions in Laravel 11 apps:

  • 1 – Create helpers.php File
  • 2 – Add File Path In composer.json File
  • 3 – Run Command for autoloading
  • 4 – To Use Custom helper function in laravel blade
  • 5 – To call helper function in laravel controller

1 – Create helpers.php File

To create helpers.php in the laravel project inside the app directory. And can write our own custom functions and call anywhere in your laravel blade view, controller and model file.

For example, you can create a following functions in your custom helpers.php file:

<?php
 
  function random_code(){
    return rand(1111, 9999);
  }
  function allUpper($str){
    return strtoupper($str);
  }

2 – Add File Path In composer.json File

In this second step, you will add the path of the helpers file in the composer.json file. Let’s go to project root directory and open composer.json file and update the below-given code into the file:

    "autoload": {
        "psr-4": {
            "App\\": "app/",
            "Database\\Factories\\": "database/factories/",
            "Database\\Seeders\\": "database/seeders/"
        },
           "files": [
            "app/helpers.php"
        ]
    },

3 – Run Command for autoloading

In this final step, go to command prompt and type the given command:

composer dump-autoload

After run the above command on command prompt. Then you can use custom helper functions by calling this functions name.

4 – To Use Custom helper function in laravel blade

You can see the following example of how to call helper function in laravel blade view file:

<h2><?php echo allUpper('I am from lara.com') ?></h2>

5 – To call helper function in laravel controller

You can see the following example of how to call helper function in laravel controller file:

    public function index()
    {   
        $data['title'] = toUpper('Title');
        return view('view', $data);
    }

Conclusion

In this tutorial, you have learned how to create helper and functions in laravel 8. And as well as how to use/call helper functions in laravel 8 on blade view, controller file.

Recommended Laravel Tutorials

Leave a Comment