Wednesday, December 25, 2024
Google search engine
HomeLanguagesHow to Use Helper Function in Laravel 8

How to Use Helper Function in Laravel 8

Before you call/use the helper function in laravel 8, you need to create a helpers.php file inside the app directory.

Laravel 8 custom helper. In this tutorial, you will learn how to create a custom helper in laravel 8. And how to call the helper function in laravel 8 on blade view, controller, and model files.

Note that, Laravel 8 custom helper helps to reduce the re-writing the same code again and again. In this custom helper tutorial, we will show you an example of how you can create a function in your custom helper and how to call this function.

How to Create Helper and Function in Laravel 8

1 – Create helpers.php File

In this step, you need create helpers.php in the laravel project inside the app directory.

In this file, you 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:

composer.json

    "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.

How to use helper function in laravel

Now, you will learn how to call or use above created custom helper function in laravel 8 by examples:

1 – How to call 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 geeksforgeeks.org') ?></h2>

2 – How 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 Posts

RELATED ARTICLES

Most Popular

Recent Comments