如何从Laravel中的路线调用辅助方法 [英] How to call a helper method from routes in Laravel

查看:73
本文介绍了如何从Laravel中的路线调用辅助方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通常我们从如下所示的路由中调用控制器方法

Normally we called a controller method from route like below

Route::get('/route_name', 'controllerName@method');

但是有什么方法可以从route调用辅助方法吗?

But is there any way to call a helper method from route ?

推荐答案

步骤1 第一个非常简单明了.只需转到位于Laravel项目中的composer.json文件

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/"
    }
},

更改composer.json文件并向files数组添加新路径后,需要转储自动加载器.只需从Laravel项目目录中的终端运行此命令即可.

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

现在,您的帮助程序文件将自动加载到您的Laravel项目中.

Now your helper file will be automatically loaded in your Laravel project.

第2步 如果您的帮助程序文件包含具有这些帮助程序方法的类,并且您已指定了名称空间,则可以通过定义别名来轻松使用它们.您可以通过在config/app.php文件中的aliass数组的末尾添加以下内容来轻松地做到这一点.

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.

用别名写'Helper' => App\Helpers\Helper::class,

第3步现在,在您的web.php中,您可以使用帮助器功能

Step 3 Now in your web.php you can use helper function

Route::post('/area/getAreaList', function() {   
    Helper::getAreas();
})->name('area.getAreaList');

这篇关于如何从Laravel中的路线调用辅助方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆