Laravel querying array - php

I am trying to create a eloquent query to get the user results of an array of user id's. Is there a clean way to accomplish this using elequent instead of chaining wheres like this:
$users = User::where('id', '=', '1')->orWhere('id','=','2')
My array of ids comes from an API call and can contain as many id's as the call passes.
Cheers!

You want to use whereIn. This lets you pass in an array of IDs.
$userIds = [1, 2];
$users = User::whereIn('id', $userIds)->get();

Related

Laravel 5.6 groupBy on collection doesn't work

GroupBy just doesn't work on collection in Laravel 5.6, it is very annoying when simple things which supposed to work not wirking...
$users = Game::orderBy('game_count', 'desc')->get();
$users_grouped = $users->groupBy('user_id');
As you might guess $users_grouped contains the same collection as $users with the same repeating user_id values.
I don't get why it doesn't work as expected and how to fix it?
At least GROUP BY works with raw DB select hopefully.. But I want to use Eloquent..
You're confusing eloquent's query builder with collections. They are not the same thing.
groupBy on a query builder instance will use an SQL GROUP BY and give one aggregated result for the column(s) you are grouping on.
groupBy on a collection instance will return a new collection that groups all collected items by the given key's value.
https://laravel.com/docs/5.6/collections#method-groupby
If you want to use the query builder's groupBy method, chain it before the get():
$users = Game::orderBy('game_count', 'desc')->groupBy('user_id')->get();
get() executes the query and returns the collection of records.
If you want to group the query by user_id just do the groupBy before the get(), as the following row:
$users = Game::orderBy('game_count', 'desc')->groupBy('user_id')->get();
The rows will be the same. You should make two querys:
$users = Game::orderBy('game_count', 'desc')->get();
$users_grouped = Game::orderBy('game_count', 'desc')->groupBy('user_id')->get();
Temporary solution for this is the raw SQL query:
$users_grouped = DB::select('SELECT COUNT(id) AS theCount, `user_id` from `quiz_games` GROUP BY `user_id` ORDER BY theCount DESC');

Laravel Eloquent query JSON column with Where In?

I am having trouble querying a json column.
Previously my code was
$query->whereIn('user', $users);
Now i have changed the db type to JSON column and am trying to modify the code for the new version.
In RAW MYSQL this works
JSON_CONTAINS(user, '"tom","Bill"')
But when i put it in eloquent / php it keeps failing or returning noting. Here i am passing in an array of Users, previous using an WhereIn which works in raw SQL
$leads->whereRaw("JSON_CONTAINS(user, '"$users"')")
Any idea how to make it work in Laravel so i can pass in an array of strings, query them against the json column which contains an array of strings too.
My Json colum has data like so
["Paul", "Tom", "Bob"]
MySQL expects a JSON string:
$leads->whereRaw('JSON_CONTAINS(user, ?)', [json_encode($users)])
In Laravel 5.6.24 you can use whereJsonContains():
$leads->whereJsonContains('user', $users)
If $users is array of names then you should iterate over it and add orWhereRaw condition, note that orWhereRaw can accept an array of parameter:
$users = ["Tom", "Bob"];
foreach( $users as $user) {
$leads->orWhereRaw("JSON_CONTAINS(user, ?)", [$user]);
}
$leads = $leads->get();

Laravel convert resultset to array

Database table SITE has many columns. One of them is site_id. I need all the site_ids as an array since it has to be fed to a method which accepts only a string array.
What I tried so far is:
$sites = DB::select('select site_id from site_tab');
$sites_arr = $sites->toArray();
But this doesn't produce the result I want. I need $sites_arr to be like ['A','B','C',...]
Please suggest a way to get this done. A solution based on Eloquent is also OK for me.
Thanks
Try this:
DB::table('site_tab')->pluck('site_id')->toArray();
reference pluck
referen toArray
If you open a manual, you will see that
The select method will always return an array of results
So, there's no need to use ->toArray(), as result is already an array.
To get values as array of names you can do:
$site_ids = DB::table('site_tab')->pluck('site_id');
Using ->toArray() here is optional, as you can iterate over $site_ids (which is a Collection) with a foreach too.

Grouping multiple where clauses with OR in Laravel on one single orWhere function

I want to select from the database something like: SELECT * FROM database WHERE id=1 OR id=2 OR id=5;
I do not know the number of the where clauses that the user will request, it can be one, it can be 10.
I tried using Model::orWhere([['id','=',1],['id','=',2],['id','=',5]]) but it seems to be returning an empty list.
In the Laravel documentation, there is this example for the WHERE clause:
users = DB::table('users')->where([
['status', '=', '1'],
['subscribed', '<>', '1'],
])->get();
While the WHERE clause it working as in the example, orWhere clause doesn't seem to work like this though.
Following on from my comment you can us an IN Clause could solve this.
$model = Model::whereIn('id', array(1, 2, 3))->get();
Reference How to Make Laravel IN clause
Use something like:
User::whereIn('id', [1, 2, 3])->get();
As second parameter you need to use an array.

Retrieve Laravel Model results based on multiple ID's

I have implemented ZendSearch into my Laravel application. I am using it as my search engine where users will type a search word, and then ZendSearch will return me an array of results ordered by relevance. However, the array that ZendSearch returns, only returns my record ID's (it doesn't return any of the actual record information).
What would next be the correct way to query my Model to retrieve the results based on the ZendSearch array results which is just an array of ID's ordered based on relevance.
I know of Model::find(1) which would return my record with an ID of 1, but how can I feed that find() method an array of ID's that I want to be returned in the order I am giving it.
That's simple. Use findMany:
$models = Model::findMany([1, 2, 3]);
By the way, you can also pass an array to find() and it will internally call findMany:
$models = Model::find([1, 2, 3]);
Under the hood it just does a whereIn so you could do that too:
$models = Model::whereIn('id', [1, 2, 3])->get();
Just use ->find($ids)
$ids = [1,2,3,4]
$model = Model::find($ids);
in my case, i use query like this
$ids = [1,2,3,4]
$model = Model::query()->find($ids);
I used that in Lumen.

Categories