Laravel中如何用同一路由URL对应两个控制器方法实现单页加载多图表
可行解决方案
完全可以保留dashboard URI,给你提供两种常用实现方案:
方案1:单方法合并所有数据(适合数据量小的场景,实现最简单)
你不需要写两个路由,只需要在同一个控制器方法里把所有图表需要的数据一次性查询完成,传给视图即可。
- 首先补充你需要的面积图数据查询方法,示例逻辑如下:
// 补充到DashboardController中 public function getMonthlyTrendData() { // 按你的业务需求写面积图的查询逻辑,以下是参考示例 $trendData = collect(range(1, Carbon::now()->month))->map(function ($month) { $monthlyInvoice = Sales::whereYear('created_at', Carbon::now()->year) ->whereMonth('created_at', $month) ->where('payment_type', 'credit') ->sum('balance'); $monthlySales = Sales::whereYear('created_at', Carbon::now()->year) ->whereMonth('created_at', $month) ->where('payment_type', 'cash') ->sum('payment'); return [ 'month_name' => Carbon::create()->month($month)->format('m月'), 'invoice_amount' => $monthlyInvoice, 'sales_amount' => $monthlySales ]; }); return $trendData; }
- 扩展你现有的
createChartStats方法,把面积图数据合并到返回参数中:
public function createChartStats() { $chartData = [ // 原有4个统计图表数据 'todays_invoices' => $this->getTodaysInvoices(), 'this_months_invoices' => $this->getThisMonthsInvoices(), 'todays_sales' => $this->getTodaysSales(), 'this_months_sales' => $this->getThisMonthsSales(), // 新增面积图数据 'monthly_trend' => $this->getMonthlyTrendData() ]; return view('dashboard', compact('chartData')); }
- 路由只保留一条即可:
Route::get('dashboard', [DashboardController::class, 'createChartStats']);
之后你直接在dashboard.blade.php里用$chartData变量里的所有数据渲染所有图表即可。
方案2:AJAX异步加载(适合数据量大、需要提升页面加载速度的场景)
路由分基础页面路由和数据接口路由,页面加载后异步拉取各个图表的数据渲染:
- 路由配置:
// 返回dashboard基础空白页面 Route::get('dashboard', [DashboardController::class, 'index']); // 统计卡片数据接口 Route::get('dashboard/api/stats', [DashboardController::class, 'createChartStats']); // 面积图数据接口 Route::get('dashboard/api/monthly-trend', [DashboardController::class, 'getMonthlyTrendData']);
- 控制器方法调整:把数据方法改成返回JSON格式即可
public function createChartStats() { $chart_stats = [ 'todays_invoices' => $this->getTodaysInvoices(), 'this_months_invoices' => $this->getThisMonthsInvoices(), 'todays_sales' => $this->getTodaysSales(), 'this_months_sales' => $this->getThisMonthsSales(), ]; return response()->json($chart_stats); } // getMonthlyTrendData方法同理返回JSON
- 页面中用JS分别调用两个接口,拿到数据后渲染对应图表即可。
内容的提问来源于stack exchange,提问作者Jumar Juaton
相关产品推荐
相关产品推荐

