How to call a controller function inside a view in

2019-01-09 04:30发布

In laravel 4 i just used a function

$varbl = App::make("ControllerName")->FunctionName($params);

to call a controller function from a my balde template(view page). Now i'm using Laravel 5 to do a new project and i tried this method to call a controller function from my blade template .But its not working and showing some errors. Is there any method to call a controller function from a view page in Laravel 5?

标签: php laravel-5
8条回答
Ridiculous、
2楼-- · 2019-01-09 05:13

Controllers methods are not supposed to be called from the view. Best options are to call the method from the method which is returning the view object, which contains the output which you then can echo in the view;

    public function bar() {
        $foo = $this->foo();
        return view( 'my.view', compact( 'foo' ) );
    }

    protected method foo()
    {
        return 'foobar';
    }

second option to add a helpers file to the compose.json file

"autoload": {
    "files": [
        "app/helpers.php"
    ]
},

dump your autoload and you can call these functions from anywhere inside your application

查看更多
叛逆
3楼-- · 2019-01-09 05:15

You can actually call a class, helper class or any declared class in your blade template but putting it in the aliases array of your app.php in the config folder

        'Helper' =>   App\Http\Helpers\Helper::class,

Using the Helper as an alias, you can reference it in your blade template, example below:

        {{Helper::formatDateToAgo ($notification->created_at)}}                                                
查看更多
登录 后发表回答