如何计算数据库中的行数并显示在 laravel 7 中

How to get count number of rows in database and show in laravel 7

我需要获取打开的职位数并在视图中显示。有 6 个空缺职位。我需要在绿框中显示 6。请看附件

 <!-- opend job view -->
        <!-- ./col -->
          <div class="col-lg-3 col-6">
            <!-- small box -->
            <div class="small-box bg-success">
              <div class="inner">
                <h3>53<sup style="font-size: 20px">%</sup></h3>
    
                <p>Opened</p>
              </div>
              <div class="icon">
                <i class="fas fa-box-open"></i>
              </div>
              <a href="opened" class="small-box-footer">More info <i class="fas fa-arrow-circle-right"></i></a>
            </div>
          </div>

 <!-- opend job controler-->
public function open_count ()
    {
        $pend_counts = Job::where('state','Closed')->count();
        // return view('jobs.closed_job',compact('closed'));
        // $count = App\Flight::where('active', 1)->count();
    }

 <!-- Route-->
Route::get('/open_c','JobController@open_count');

您必须在控制器中获取计数并将其传递给视图(不要忘记这一点):

public function open_count ()
    {
        $opened_counts = Job::where('state','Closed')->count();
    
        //Add the $opened_counts variable to the compact function
        return view('jobs.closed_job',compact('opened_counts'));
       
    }

在您的 Blade 文件中,您可以调用 {{$opened_counts}} 来显示变量。

<div class="col-lg-3 col-6">
            <!-- small box -->
            <div class="small-box bg-success">
              <div class="inner">
                <h3> {{$opened_counts}} <sup style="font-size: 20px">%</sup></h3>
    
                <p>Opened</p>
              </div>
              <div class="icon">
                <i class="fas fa-box-open"></i>
              </div>
              <a href="opened" class="small-box-footer">More info <i class="fas fa-arrow-circle-right"></i></a>
            </div>
          </div>

如果您需要百分比而不是绝对值,您可以将控制器更改为(您还需要处理除以 0 的错误):

public function open_count ()
    {
        $opened_counts = Job::where('state','Closed')->count();
        $percentage = $opened_counts / Job::all()->count();
    
        //Add the $opened_counts variable to the compact function
        return view('jobs.closed_job',compact('opened_counts', 'percentage'));
       
    }