Reputation: 433
Normally we called a controller method from route like below
Route::get('/route_name', 'controllerName@method');
But is there any way to call a helper method from route ?
Upvotes: 0
Views: 3849
Reputation: 1474
Step 1 First one is pretty easy and straightforward. Simply go to composer.json file located in your Laravel project
"autoload": {
"files": [
"app/Helpers/Helper.php"
],
"classmap": [
"database/seeds",
"database/factories"
],
"psr-4": {
"App\\": "app/"
}
},
After changing composer.json file and adding a new path to the files array, you need to dump the autoloader. Simply run this command from the terminal in your Laravel project directory.
composer dump-autoload
Now your helper file will be automatically loaded in your Laravel project.
Step 2 If your helper file involves a class that has those helper methods and you have specified namespace, you could use them with little effort by defining an alias. You can do that easily by adding the following at the end of the aliases array in config/app.php file.
in alias write 'Helper' => App\Helpers\Helper::class,
Step 3 Now in your web.php you can use helper function
Route::post('/area/getAreaList', function() {
Helper::getAreas();
})->name('area.getAreaList');
Upvotes: 1
Reputation: 163748
You could use a closure:
Route::get('/route_name', function() {
helper();
});
But a better way to do this is to call a controller method and call the helper from that method:
Route::get('/route_name', 'controllerName@methodWhichWillCallHelper');
Upvotes: 0