【问题标题】:display result of function is controller inside home view blade (LARAVEL , PHP)函数的显示结果是主视图刀片内的控制器(LARAVEL,PHP)
【发布时间】:2020-05-11 14:16:41
【问题描述】:

我想在主页视图刀片中显示总金额 (表 = 付款,冒号 = 金额)

我通过路由测试了另一种方法,它工作正常,但结果当然显示在 /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,但功能索引已经使用,所以我在这个控制器中创建新功能,我试试这个

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>

【问题讨论】:

    标签: php laravel controller


    【解决方案1】:

    您可以使用with()

    public function show(){
        $total = DB::table('payments')->where('status', '=', 'success')
                                      ->sum('payments.amount'); 
        return  view('home')->with('total', $total); 
    }
    

    【讨论】:

      【解决方案2】:

      根据文档:

      The second argument is an "array" of data that should be made available to the view.

      尝试:

      return  view('home' , ['total' => $total]); 
      

      或使用-&gt;with('key',$value):

      return view('home')->with('total', $total);
      

      你也可以使用compact()函数,它是PHP的内置函数,用于使用变量创建数组:

      return  view('home' , compact("total")); 
      

      【讨论】:

      • 如何从 home.blade 调用它?
      • 以与您之前相同的方式:

        {{$total}}

      • 没用!错误页面说:未定义的变量:总计
      【解决方案3】:

      您可以使用紧凑功能发送总变量结果以查看 下面。

      return  view('home' , compact('total'));
      
      // You can call it in home.blade like this 
      
      //for example
      
      @if(isset($total ))
          <li>{{ $total }}</li>
      @endif
      

      【讨论】:

      • 如何从 home.blade 调用它?
      • 谢谢,但我用什么来代替名称 {{ $result->??}}
      • 首先你应该 dd($total) 然后你可以看到键名是什么。{{ $result->这里是你的数组键值}}
      • 在函数显示中,我将支付总额的结果存储在变量 $total 中。我不需要 aray 我只需要显示这个总数!结果必须是例如 6540.00
      • 我根据你的需要编辑我的答案,现在你可以看到了。
      猜你喜欢
      • 2017-03-12
      • 2012-12-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多