Laravel Method Steps for Configuring Global Common Functions

  • 2021-12-11 07:16:04
  • OfStack

Preface

In laravel project development, common functions are often used, so how to configure global common functions in laravel? ? The following words are not much to say, let's take a look at the detailed introduction

The method is as follows

In the Laravel project, we often need to define some global common functions. Usually, we define these common functions in a separate file, such as helpers. php. We create a file named helpers. php in the app directory (app/helpers. php) and edit it as follows:


/**
 *  String twice md5 Encryption 
 * @param $str  String to encrypt 
 */
function double_md5($str) {

 return md5(md5(trim($str)));
}

This function returns the string returned after md5 encryption of a string twice. In order for the application to find the helpers. php file correctly, it is necessary to modify the autoload configuration of composer. json in the root directory of the project:


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

Specify the file/folder to be loaded in the files array of the autoload configuration item. Remember to run composer dump-autoload after the modification is complete to make sure the modification takes effect:


composer dump-autoload
#  Or 
composer dumpautoload

Now that all functions in helpers. php are loaded into the auto-loader, you can use the functions defined in the helpers. php file in your project code.

Summarize


Related articles: