且构网

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

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

更新时间:2023-01-24 10:43:59

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

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 autorun 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.

或者如果您不需要放入助手.您可以简单地从它的控制器中调用它.只需将其设为static function即可. 创建.

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) {}

打电话.

\App\Http\Controllers\ControllerName::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 \App\Http\Controllers\ControllerName;