我想在主视图边栏选项卡中显示总金额 (表 = 付款,冒号 = 金额(
我通过路由测试了另一种方法,它工作正常,但结果当然显示在/test 中:
Route::get('/test', function(){
$total = DB::table('payments')
->where('status', '=', 'success') //this for collect only the success payments
->sum('payments.amount');
return $total; // work fine the result is correct
});
但我的目的是在主视图中显示此结果 通过将函数从以前的代码从路由移动到控制器并在视图中调用它
对于控制器,我有Homecontroller,但功能索引是aleardy使用的,所以我在这个控制器中创建新功能,我尝试这个
public function show(){
$total = DB::table('payments')
->where('status', '=', 'success')
->sum('payments.amount');
return view('home' , $total);
}
对于路由,我把这个
Route::get('/home', 'HomeController@show');
我在视图中尝试了这个,但没有工作:
<h1>{{$total}}</h1>
您可以使用with()
public function show(){
$total = DB::table('payments')->where('status', '=', 'success')
->sum('payments.amount');
return view('home')->with('total', $total);
}
根据文档:
第二个参数是应提供给视图的数据"数组"。
尝试:
return view('home' , ['total' => $total]);
或使用->with('key',$value)
:
return view('home')->with('total', $total);
你也可以使用compact()
函数,它是PHP中的一个内置函数,用于使用变量创建一个数组:
return view('home' , compact("total"));
您可以使用紧凑函数发送总变量结果以查看 下面。
return view('home' , compact('total'));
// You can call it in home.blade like this
//for example
@if(isset($total ))
<li>{{ $total }}</li>
@endif