We knows that laravel provides so many helper function build in like public_path, storage_path, config, url, route, etc.
And all are these function defined as globally, so we dose not required to include any file or method to call them.
like that we are also able to create our own helper functions in projects, and also we can call them globally too.
Now don't waste time to go in description, let's make them happen.
Step 1 : Create helper file
Create a new file in following path : /app/Http/helper.php
You can give name whatever you like.
Step 2 : Change in composer.json
We have to make changes in composer.json file which located in root of your project folder
We need to add our file in autoload like below
{
...
"autoload": {
...
"files": [
"app/Http/helper.php"
]
}
}
We changed in core of our project, so we need to refresh project files once again
Step 3 : Reload composer classes
Run below command in your terminal for generate new classes for project
composer dump-autoload
Above command will gather all require files for your project
And now you are ready to create your helper function in your custom helper file
Step 4 : Create function in custom helper file
Make method of your requirement in following path : /app/Http/helper.php
for example
<?php
...
function dashSlug($string) {
return Str::slug($string, "-");
}
Now above method is call any where in your project without making any model or controller method
Step 5 : Call custom function in controller
for example
<?php
namespace App\Http\Controllers;
...
class Controller extends BaseController {
public function index(Request $_request) {
...
$dashSlugString = dashSlug($_request->string);
...
}
}
That's all done now here.