User Laravel model to query using an array - php

I've got a Laravel model, but i'd like to search the table according to an array passed in.
i.e. "Return all rows whose id matches one of the array's contents"
I can see with Laravel's query builder i can search via an input array:
$users = DB::table('teams')->whereIn('id', array(1, 2, 3))->get();
But can't seem to find anywhere how to do the same using a model.
Any ideas? Cheers!

Replace DB::table('teams')-> with a static call to the model.
$users = <model name>::whereIn('id', array(1, 2, 3))->get();

You can try this.
<?php
use App\Models\Team;
$users = Team::whereIn('id', array(1, 2, 3))->get();

Related

How to make a DB call with an array of ids and get the first row of every of those ids? [duplicate]

I want to make query in Laravel Eloquent like here its raw MySQL query
SELECT * from exampleTbl where id in(1,2,3,4)
I have tried this in Laravel Eloquent but it's not working
DB::where("id IN(23,25)")->get()
Here is how you do in Eloquent
$users = User::whereIn('id', array(1, 2, 3))->get();
And if you are using Query builder then :
$users = DB::table('users')->whereIn('id', array(1, 2, 3))->get();
If you are using Query builder then you may use a blow
DB::table(Newsletter Subscription)
->select('*')
->whereIn('id', $send_users_list)
->get()
If you are working with Eloquent then you can use as below
$sendUsersList = Newsletter Subscription:: select ('*')
->whereIn('id', $send_users_list)
->get();
Syntax:
$data = Model::whereIn('field_name', [1, 2, 3])->get();
Use for Users Model
$usersList = Users::whereIn('id', [1, 2, 3])->get();
As #Raheel Answered it will be fine but if you are working with Laravel 6/7
Then use Eloquent whereIn Query.
Example1:
$users = User::wherein('id',[1,2,3])->get();
Example2:
$users = DB::table('users')->whereIn('id', [1, 2, 3])->get();
Example3:
$ids = [1,2,3];
$users = User::wherein('id',$ids)->get();
Since Laravel 5.7, there is a method whereIntegerInRaw. The execution time is faster than whereIn.
User::whereIn('id', [1, 2, 3])->get();
User::whereIntegerInRaw('id', [1, 2, 3])->get();
You can see the PR.
Maybe you wanna use whereRaw($query)
Your Code :
DB::where("id IN(23,25)")->get()
Into :
DB::whereRaw("id IN(23,25)")->get()

Laravel whereIn issue

Good day,
I wanted to do something like this:
$ids = [1, 2, 3];
$posts = $user->posts()->whereIn('id', $ids)->get();
but I get an Internal Server Error. Is there a different way to do this?
For the sake of this example, assume ID is not the primary key and that multiple posts can have the same ID. So this:
$ids = [1, 2, 3];
$posts = Post::whereIn('id', $ids)->get();
wouldn't return the desired results.
The reason you are having the error is mysql is unable to what table you are referring with id column. Use tableName in whereIn() clouse
$posts = $user->posts()->whereIn('posts.id', $ids)->get();
N.B: I assume your Post table name is posts
please use like
$items = DB::table('items')->whereIn('id', [1, 2, 3])->get();
link : Laravel ->where('id', ARRAY). multiple where conditions laravel 4
And
User::select('id','name','email','phone','created_at')->whereIN('id',[1,2,3,4,5,6,7,8,9,9,10,11])->where('is_guest',NULL)->where('user_type','1')->orderBy('id','desc')->take(20)->get();
also work with laravel 5.4

"Skip" method in a Laravel Collection

In the Query Builder (\Illuminate\Database\Query\Builder), it is possible to use both the skip($n) and take($n) methods.
In a Collection (\Illuminate\Support\Collection), it's possible to use the take($n) function, but there is no skip($n) function.
Why is that and is there an alternative?
The skip($n) method is indeed not included in the Collection class, but there is a function that does the same: slice($n).
QueryBuilder (taken from the documentation):
$users = DB::table('users')->skip(10)->take(5)->get();
Alternatively, you may use the limit and offset methods:
$users = DB::table('users')
->offset(10)
->limit(5)
->get();
Collection:
collect([1, 2, 3, 4])->slice(2)->all(); //[3, 4]
Many of the methods in the QueryBuilder class are not available in the Collection class, and vice-versa. But both of them have similar functions, like QueryBuilder's where function, you'd use Collection's filter function to achieve similar results.
The forPage method returns a new collection containing the items that would be present on a given page number. The method accepts the page number as its first argument and the number of items to show per page as its second argument:
$collection = collect([1, 2, 3, 4, 5, 6, 7, 8, 9]);
$chunk = $collection->forPage(2, 3);
$chunk->all();

Laravel foreach iterate only one time though item that has same ids

I am retrieving users using many to many relationships. I want to loop through the user only one time that have two entries in pivot.
e.g.
$admin = Admin::first();
$users = $admin->users;
foreach($users as $user) {
//Iterate through users that has different ids
//Do not iterate over same user twice
}
Nothing wrong with your code just use all() OR get() instead of first().
Or if you have multiple entries with single admin please share your model code
If you dont need the duplicate user entries, it is also possible to avoid the duplicates in the $admin->users collection by using the distinct method:
$admin = Admin::first();
$users = $admin->users()->distinct()->get();
https://laravel.com/docs/5.5/queries#selects
I found the solution myself. array_unique($array) was the solution. I pushed user ids to $users array and used array_unique($users).Thanks to php.net.
Ref. http://php.net/manual/en/function.array-unique.php
<?php
$input = array(4, "4", "3", 4, 3, "3");
$result = array_unique($input);
var_dump($result);
?>

Laravel Eloquent - find order

I am getting 3 records from my database
return \App\Work::find([12, 2, 3]);
The annoying thing is they are reordered by when I pass them the to the view.
Is there a way to retain the order they are 'found'?
MySQL allows you to specify an order for a given field using this syntax:
SELECT * FROM work ORDER BY FIELD(id, 12, 2, 3);
Combine that with Eloquent's orderByRaw() method (https://laravel.com/api/5.5/Illuminate/Database/Query/Builder.html#method_orderByRaw) and you should be able to do something like this:
return \App\Work::whereIn('id', [12, 2, 3])->orderByRaw('FIELD (id, 12, 2, 3)')->get();
The find() method won't work with this because it returns the object immediately, so we need to use a WHERE IN clause for the ID instead. Obviously it will need a bit of refactoring as currently the ID's are duplicated, but this should achieve what you want.
Try sortBy like this
return \App\Work::find([12, 2, 3])->sortBy(function($el){
return array_search($el->getKey(), [12, 2, 3]);
}
About getKey

Categories