Parth Pandya
Parth Pandya

Reputation: 1045

How to pass the Auth::user() in the existing query?

I have a query which selects a column value from the database and that value is passed to a variable which is further passed to a view with the compact method.

The query is as follows:-

$activated_up = User::where(function($query) {
    $query->where('activated_up', '=', '1')
          ->orWhere('activated_up', '=','0');

    })
    ->get(['activated_up']);

It is working fine. But it only gets the activated_up field so if there is only one user in database than it works fine but if there are multiple user than I need to consider Auth::user() in order to differentiate and select the current user only which is not possible with this existing query.

So I tried updating it with the having method.

$activated_up = User::where(function($query) {
    $query->having('id_user', Auth::user()->id_user)
          ->where('activated_up', '=', '1')
          ->orWhere('activated_up', '=','0');

    })
    ->get(['activated_up']);

But is doesn't work. I also tried with the union method like below:-

$id = User::where('id_user',Auth::user()->id_user)->first();
$activated_up = User::where(function($query) {
    $query->where('activated_up', '=', '1')
          ->orWhere('activated_up', '=','0');
          ->union($id);

    })
    ->get(['activated_up']);

But this also not works. I need to make it work anyway.

What change is needed to obtain desired result?

Upvotes: 1

Views: 68

Answers (1)

Babak Asadzadeh
Babak Asadzadeh

Reputation: 1237

you should just do this:

$activated_up = User::where('id_user',Auth::user()->id_user)
->where(function($query) {
$query->where('activated_up', '=', '1')
      ->orWhere('activated_up', '=','0');
})
->get(['activated_up']);

Upvotes: 3

Related Questions