Gonçalo Bastos
Gonçalo Bastos

Reputation: 421

How to get all clients that are blocked by acessing other table to get it

I have a big project on my hands and I have a big problem!

Dont worry all data is fake, generated by laravel

So I have a table like this where the foreign and primary key is the same:

enter image description here

With this foreign key I can acess to another table:

enter image description here

And I need to get all the users that have the field "bloqueado" at 1.

The problem is that I dont get it, like I has tryed so many commands, that I dont know anymore!

This is my controller where where I received the status, so the admin can filter if he wants only "bloqueado" at 1 or "bloqueado" at 0

I can acess to "bloqueado" field for each user, like this example:

//Example//
    $clientes = Clientes::all();
    $clientes[0]->user->bloqueado;
    But how can I get only all "clientes" that the "bloqueado" field is equal to $status?
//End of Example//

    $status = $request->status ?? '';

    $qry =  Clientes::query();

    if ($status) {
        //$qry->where('bloqueado', $status);
    }

    $clientes = $qry->paginate(10);
    return view('clientes.index')
        ->withClientes($clientes)
        ->withSelectedStatus($status);

Upvotes: 1

Views: 68

Answers (1)

Muhammad Inaam Munir
Muhammad Inaam Munir

Reputation: 1260

You can use whereHas. Check this documentation: https://laravel.com/docs/8.x/eloquent-relationships#querying-relationship-existence

You can use the following code to get all clients which have user with status equal to $status

$status = $request->status ?? '';

$clientes = Clientes::whereHas('user', function($query) use ($status){
    $query->where('bloqueado', $status)
})->paginate(10)

return view('clientes.index')
    ->withClientes($clientes)
    ->withSelectedStatus($status);

Upvotes: 1

Related Questions