count results from the controller


With the following code I have to search in a BD = payments and if 'payment_date' is equal to today I will show it in the view. And according to what I found, I added an accountant. If you found 2 results the value of the variable $ varnum = 2. But my question is how can I do the same without going to a view, direct from the controller. My goal is if I find 2 that match "today" I can save it in a BD = system-> numph. Even if there are suggestions in my vision code, I accept them because I am just learning.

I have a driver (UpdateController.php)

public function index(Request $request)
$hoy = \Carbon\Carbon::now()->toDateString();
$payments = Payment::searchdatepay($hoy)->orderBy('id','ASC')->paginate(10);
return view('update.update')->with(['payments'=> $payments, 'varnum' => 0]);

a scope (Payment.php)

protected $table = "payments";
protected $fillable = ['loan_id', 'id', 'pago', 'pagado', 'motivo', 'estado', 'fecha_pago', 'fecha_promesa', 'pago_abono', 'pago_adeudo', 'dias_atraso', 'asesor', 'remember_token', 'created_at', 'updated_at'];

public function scopeSearchDatePay($query, $var)
return $query->where('fecha_pago','LIKE',"%$var%");

a view (update.update)


<table class="table table-striped">
        <th>Fecha de Pago</th>

        @foreach($payments as $payment)
            <td>{{ $varnum = 1 + $varnum }}</td>
            <td>{{ $payment -> id }}</td>
            <td>{{ $payment -> fecha_pago }}</td>
            <td>{{ $payment -> motivo }}</td>
            <td>{{ $payment -> estado }}</td>
{!! $payments-> render() !!}
<!-- Plugins -->                

asked by Luis Cárdenas 07.09.2016 в 23:43

1 answer


You're apparently looking for count () , a PHP function:

public function index(Request $request)
    $hoy = \Carbon\Carbon::now()->toDateString();
    $payments = Payment::searchdatepay($hoy)
    $varnum = count($payments);
    return view('update.update', compact('payments', 'varnum'));

I made a small improvement to your code, however there are two other improvements that I suggest:

  • It should not be the responsibility of the controller to obtain data from the database (or in this case to have contact with the Query Builder). This part should be delegated to a service, job, repository or similar.
  • To respect PSR-2 , which is used by Laravel, you should declare Carbon with use , something like this:

    use Carbon\Carbon;
    class PaymentController // ....
        // ...
        public function index(Request $request)
            $hoy = Carbon::now()->toDateString();
            // ...
answered by 08.09.2016 / 00:03