且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 Laravel 5 的视图中调用控制器函数

更新时间:2023-01-24 11:31:50

如果你有一个在多个地方使用的函数,你应该在 helpers 文件中定义它,为此在 app/Http 中创建一个(可能是)/Helpers 文件夹并将其命名为 helpers.php,在 composer.json 的 autoload 块中以下列方式提及此文件:

If you have a function which is being used at multiple places you should define it in helpers file, to do so create one (may be) in app/Http/Helpers folder and name it helpers.php, mention this file in the autoload block of your composer.json in following way :

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

运行composer dump-autoload,然后你就可以在任何地方调用这个函数了,不管是控制器视图还是模型.

run composer dump-autoload, and then you may call this function from anywhere, let it be controller view or model.

或者如果您不需要放入助手.你可以简单地从它的控制器调用它.只需将其设为静态函数.创建.

or if you don't need to put in the helpers. You can just simply call it from it's controller. Just make it a static function. Create.

public static function funtion_name($args) {}

打电话.

AppHttpControllersControllerName::function_name($args)

如果你不喜欢很长的代码,你可以自己制作

If you don't like the very long code, you can just make it

ControllerName::function_name($args)

但不要忘记从视图页面的顶部调用它.

but don't forget to call it from the top of the view page.

use AppHttpControllersControllerName;