第一种
app/Helpers/ViewHelper.php 创建一个辅助函数,用于动态确定视图路径:
<?php
if (!function_exists('fetchView')) {function fetchView($data = []){$currentAction = \Route::currentRouteAction();list($controller, $method) = explode('@', $currentAction);$viewPath = 'admin.' . strtolower(str_replace('Controller', '', class_basename($controller))) . '.' . $method;return view($viewPath, $data); // 将数据传递给视图}
}
接下来,在控制器中使用这个辅助函数来自动定位视图文件:
public function index(Request $request)
{$data = ['title' => '首页','content' => '欢迎来到首页!'];return fetchView($data); // 将数据传递给视图
}
在视图中使用参数
<!DOCTYPE html>
<html>
<head><title>{{ $title }}</title>
</head>
<body><h1>{{ $title }}</h1><p>{{ $content }}</p>
</body>
</html>
第二种
protected function view($data)
{$currentAction = \Route::currentRouteAction(); // 获取当前路由的控制器方法名list($controller, $method) = explode('@', $currentAction);// 根据控制器和方法名确定视图路径$viewPath = 'admin.' . strtolower(str_replace('Controller','',class_basename($controller))) . '.' . $method;return view($viewPath)->with(['data'=>$data]);
}
public function index(Request $request)
{$data = 'test'; // 传参数据return $this->view($data);
}