random2137
random2137

Reputation: 138

In Laravel, counting users and returning status

I have to create a route where I need to check the number of tickets from a user, their status and their dates.

It's database returns me the id from the ticket, the user_id that the ticket is related to, the status of the ticket and its expiration_date.

So for example, let's say that the user 100 has 2 tickets with the status 'expirate' at the date of 2019-01-10 and has 2 more tickets with the status of 'not_used' at the date of 12-01-2019.

So, I have to return something like that:

User 100
{
    "count": 2,
    "expiration_date": 2019-01-10,
    "status": expirate, 
},
{
    "count": 1,
    "expiration_date": 2019-01-12,
    "status": not_used, 
}

Since I'm new to Laravel, I'm trying to use it ows tools. My controller is something like that.

Controller.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use DB;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class UsersCreditsController extends Controller 
{
    public function getUsersCredits()
       {
        $users = DB::select('select user_id from users_credits');
        return view('users_credits',['users'=>$users]);
    }
}

My idea is to make a foreach to count each user_id registered in the db. Then, look for each id and group then by their status.

Is there a better way to do that using Laravel?

Upvotes: 0

Views: 379

Answers (1)

syntaqx
syntaqx

Reputation: 2866

Yes! There is an eloquent method for this:

$users = DB::table('users')->count();

I recommend checking out the section in the Laravel docs on Aggregates within queries for a deeper explanation of what's going on here.

For a quick MySQL explanation, check out the COUNT function.

Upvotes: 2

Related Questions