Mostafa Abedi
Mostafa Abedi

Reputation: 541

Laravel Eloquent - Get a specific row and others

In my users table i want to get admin user and the others who are activated. in fact the result that I want is concatenation of this two query result :

User::where('user_name','admin')->first();
User::where('is_active',1)->get();

is there any way to get this result in one query?

Upvotes: 0

Views: 852

Answers (5)

ManojKiran
ManojKiran

Reputation: 6341

Sorry for the late reply everybody missed the laravel out of box method which accepts array

Eloquent Version
User::where(['user_name' => 'admin','is_active' => '1'])->first();

Another Method

DB Facade Version

DB::table('users')->where(['user_name' => 'admin','is_active' => '1'])->first();

Hope its helps

Upvotes: 1

Vinod Joshi
Vinod Joshi

Reputation: 176

$query = User::where('is_active',1)->where('user_name','admin')->first();

Above Query will give you only one Active User whos user_name is admin and active.

As per my understanding from your question you want all users who are "active" and whos user_name is "admin" then try this below query.

$query = User::where('is_active',1)->orWhere('user_name','admin')->get();

Hope this may solve your problem.

Upvotes: 2

user10186369
user10186369

Reputation:

You should try this:

 $rsltUser = User::where('is_active',1)
       ->orWhere('user_name', 'admin')
       ->get();

Upvotes: 1

Md.Sukel Ali
Md.Sukel Ali

Reputation: 3065

Try this,

  User::where('is_active',1)
       ->orWhere('user_name', 'admin')
       ->get();

Upvotes: 1

Petay87
Petay87

Reputation: 1773

You need to use a Union to put the two result sets together.

$first = User::where('user_name','admin')->first();
$users = User::where('is_active',1)->union($first)->get();

That should get you the first Admin user AND all the active users.

In fact, as they are on the same table, a OR should also work like below:

$users = User::where('is_active',1)
             ->orWhere('user_name', 'admin')
             ->get();

I'll leave both parts in as both will work.

Upvotes: 1

Related Questions