Laravel: Consultation with Eloquent using count

1

I want to make a query that involves a count, and it works. The query is this:

$user = Auth::user();
$id = $user->id;
$users = DB::table('cuentas as a')
        ->join('pasajeros as b', 'b.id', '=', 'a.pasajero_id')
        ->where('b.usuarios_id', $id)
        ->select(DB::raw('count(*) as user_count'))
        ->get();
return $users;

The return $ users brings me this:

  

[{"user_count": 0}]

And it's fine, I have 0, because there's still no record where the user's id is contained. But what I need to do is that the content of $ users is only the number, in that case, the 0. In order to use it in an if, otherwise, that $ users is not a number like that.

    
asked by YelloWhale 10.07.2016 в 01:51
source

2 answers

2

The result is an object in an array, which results in Eloquent's get () method, for this reason it should be easily accessible in the following way

echo $users[0]->user_count;

This way, you call the first element of the array (which is a user object) and then call its property user_count.

You could also use the first() method to get the first object directly and not need to call the first element of the array:

$users = DB::table('cuentas as a')
    ->join('pasajeros as b', 'b.id', '=', 'a.pasajero_id')
    ->where('b.usuarios_id', $id)
    ->select(DB::raw('count(*) as user_count'))
    ->first();

echo $users->user_count;
    
answered by 10.07.2016 / 02:34
source
1

In laravel 5.2 you can use the function withCount to which you pass the relation as parameter.

$users = DB::table('cuentas as a')
    ->join('pasajeros as b', 'b.id', '=', 'a.pasajero_id')
    ->where('b.usuarios_id', $id)
    ->withCount('nombre_de_tu_relacion')
    ->first();

Then you call it $ users- > name_of_your_relation _count.

To graph it better: Suppose you want to count the users, just as you have in your example, you should only use withCount('users') (or whatever your relationship is called) and then call it as $users->users_count . Pretty simple and understandable.

Or in case you want to continue using the code you have, you can "clean" it a little bit more using selectRaw .

 $users = DB::table('cuentas as a')
    ->join('pasajeros as b', 'b.id', '=', 'a.pasajero_id')
    ->where('b.usuarios_id', $id)
    ->selectRaw('count(*) as user_count')
    ->first();

Greetings.

    
answered by 27.07.2016 в 12:49