[英]Laravel: multiple views for one controller
我的控制器中有一个名为 index 的 function ,我在其中返回视图页面。 我需要相同的 function 用于另一个视图页面。 如何重复使用相同的 function 而不必制作相同的 function 两次?
你的问题对我来说不够清楚。 但我希望你需要一些全局变量。 您可以在 controller 中创建私有 function 并使用 $this->this->variableName 在 controller 中的任何位置调用它,或使用 $this->this->variableName 创建全局变量并访问它们。
If you only want to reuse the function in the same controller, add a private function to that controller which performs the shared functionality and call this from your desired methods:
class YourController extends Controller
{
public function index()
{
$shared = $this->sharedFunction();
return view('index', compact('shared'));
}
public function otherFunction()
{
$shared = $this->sharedFunction();
return view('other', compact('shared'));
}
/**
* Perform shared functionality
*/
private function sharedFunction()
{
return 2 + 2;
}
}
Alternatively, if you need to share functionality across controllers, you might want to create a base controller that you use to extend your controller, but extends the Laravel controller.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.