[英]How to call class method inside a Laravel view?
I'm trying to find a way to call a method from within my class file inside a blade file. 我试图找到一种方法,可以从刀片文件中的类文件中调用方法。
foo()
uses the $item
variable from the foreach loop. foo()
使用foreach循环中的$item
变量。 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. 由于我正在刀片文件中循环,因此我无法(或者更确切地说,)在视图中调用控制器方法是不明智的,或者我听说过。
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 view.blade.php
@foreach ($data as $item)
<td>{{$item->key}}</td>
<td>{{ //myController::foo($item) is Essentially the output I need }} </td>
@endforeach
Since $item
is generated in the foreach
(which is inside the view), I don't know how to call method before it's past to the view in the return statement. 由于
$item
是在foreach
(位于视图内部)中生成的,因此我不知道如何在方法返回到return语句中的视图之前调用方法。
Any suggestions? 有什么建议么?
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,
]);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.