如何在 Laravel 视图中调用类方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36437915/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 13:32:43  来源:igfitidea点击:

How to call class method inside a Laravel view?

phplaravelfor-looplaravel-5blade

提问by Ashley Brown

I'm trying to find a way to call a method from within my class file inside a blade file. foo()uses the $itemvariable from the foreach loop. Since I'm looping inside the blade file, I'm unable, or rather, it's bad practise, to call a controller method inside a view, or so I've heard.

我正在尝试找到一种方法来从刀片文件内的类文件中调用方法。foo()使用$item来自 foreach 循环的变量。因为我在刀片文件中循环,所以我不能,或者更确切地说,这是不好的做法,在视图中调用控制器方法,或者我听说过。

MyController

我的控制器

public function getData() {
  $data = DB::paginate(10);
  return view('view', ['data' => $data]);
}

public function foo($var) {
 //do something with $var
 return $var
}

view.blade.php

视图.blade.php

@foreach ($data as $item)

 <td>{{$item->key}}</td>
 <td>{{ //myController::foo($item) is Essentially the output I need }} </td>

@endforeach

Since $itemis generated in the foreach(which is inside the view), I don't know how to call method beforeit's past to the view in the return statement.

由于$item是在foreach(在视图内部)中生成的,我不知道如何在返回语句中的视图之前调用方法。

Any suggestions?

有什么建议?

回答by jakub_jo

Just share your controller with your view:

只需与您的视图共享您的控制器:

Controller:

控制器:

public function getData() {
    $data = DB::paginate(10);

    return view('view', [
        'data' => $data, 
        'controller' => $this,
    ]);
}

View:

看法:

@foreach ($data as $item)

 <td>{{$item->key}}</td>
 <td>{{ $controller->foo($item) }} </td>

@endforeach

The better way would be to generate the output in the controller:

更好的方法是在控制器中生成输出:

public function getData() {
    $data = DB::paginate(10);

    $data = array_map(function($item) {
        $item->output = $this->foo($item);

        return $item;
    }, $data);

    return view('view', [
        'data' => $data,
    ]);
}