简体   繁体   中英

How to call a helper method from routes in Laravel

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 ?

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');

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');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM