How to add limit to array data fetched from database in laravel - php

I'm retrieving the rows from user table and I'm using below code.
<?php $user = User::get(); ?>
I want to add array limit for $user data. I don't want to use paginate();. To add limit I'm using below code but it's not working
$users = array_slice($users, 0,2);
But it's showing below error message
exception 'ErrorException' with message 'array_slice() expects
parameter 1 to be array, object given' in........
How to I add limit to $user?

<?php
$user = User::get();
$user = $user ->limit(10);
?>
try limit or
<?php
$user = User::get();
$user = $user ->take(10);
?>

In recent Laravel versions you can also use:
User::limit(10)->offset(0)->get();
Note that User model must extend Eloquent.

Do you mean to use:
$users = array_slice($user, 0,2);

You are getting the error because $users is a collection, not an array.
You could use the take method
$users = User::get()->take(3);
or the slice method
$users = User::get()->slice(3);

Here are some ways you can achieve this.
Applying the offset and limit directly to the query builder allows you to fetch only the needed rows.
$users = User::skip(5)->take(10)->get();
$users = User::offset(5)->limit(10)->get();
If you insist on working with complete result, then this approach is what to you need. You need to use collection slice method not array_slice since the result is a collection.
$users = User::all();
// Collection slice(offset, limit)
$users = $users->slice(5, 10);

Related

combine two query result set and paginate the value

I have two query result set for $users and $logged_action and merged both.If I use all() displayed all value.I want to paginate.If I include paginate(10) instead of all.I caught a error
BadMethodCallException in Macroable.php line 74: Method paginate does
not exist.
$users = DB::table('request')->select('asset_request.*')->get();
$logged_action= DB::table('status_tracker')->select('status_tracker.*')->get();
$users = $users->merge($logged_action);
$users=$users->all();
return view('layouts.approval_view',['users'=>$users]);
Maybe you can join the 2 tables by the same key that merge works and then paginate the result?
Something like that:
$users = DB::table('request')->
join('status_tracker','on' .... )->select ('asset_request.*', ....)->paginate (10);
also did not tested but you can try this:
$users = DB::table('request')->select('asset_request.*')->paginate(10);
$logged_action= DB::table('status_tracker')->select('status_tracker.*')->paginate(10);
$users = $users->merge($logged_action);
$users=$users->all();
return view('layouts.approval_view',['users'=>$users]);
Hope it helps.

Laravel collection manipulation

I have User model that has 2 fields: email and id
I have this query:
$users = User::all()->get();
the result will be 3 User objects in a Collection
I want to see the result as the following:
[87 => 'user#gmail.com', 92 => 'admin#gmail.com', 10 => 'super#gmail.com']
id will be the key and email will be the value.
Is that possible via Collection class to implement? thanks
Try:
$users = User::pluck('email','id');
You can achieve like this,
$users = User::pluck("email","id");
pluck() -> You may also specify how you wish the resulting collection to be keyed:
There is alternative to do this(playing with collections),
$users = User::all()->get();
$users = $users->pluck("email","id");
Give it a try, this will work.
try this
$users = User::all();
$data = array();
foreach ($users as $key) {
$data[$key->id] = $key->email;
}
print_r($data);
Good luck...

(Laravel) only retrieving users that have a relationship

In my site I have users and items. Users can create items. I want to get an array that has all users, where the users which have an item go first and the users which do not have an item go after.
So far I have done this:
$users = User::all();
foreach($users as $user) {
if ($user->item) {
$sortedUsers + $user;
}
// now loop again and add users without relationship
This is pretty inefficient and I'm sure there's a much better way to do it.
You can query on the existence of a relationship
$users = User::has('items')->with('items')->get();
with that syntax you are telling laravel to fetch all users that have a item and to eager load the items;
Edit:
After reading it does not look like you actually want the items just the users that have a item in that case all you need is
$users = User::has('items')->get();
Without seeing the relation of Items to Users I'm not sure if this will work but you can try the following:
$users = Users::select('users.*')->orderBy('items.id')->with('items')->get();
Or it might work with just:
$users = Users::orderBy('items.id')->with('items')->get();
Update
$users = Users::orderBy('items.id')->join('items', 'items.user_id', '=', 'users.id')->get();
you can try
$users = User::with('item')->get();
foreach ($users as $user) {
echo $User->item->name;
}
You can use has() to get users with items and doesntHave() to get users without items:
$withItems = User::has('items')->get();
$withoutItems = User::doesntHave('items')->get();
And then merge() two collections:
$users = $withItems->merge($withoutItems);
You said you want an array, so you can convert result into an array with toArray()
$array = $users->toArray();

Why do Laravel relationships prevent calls to query builder methods?

I want to find all patients that belong to a user where id = 1
This works:
$data = Patient::where('user_id', '=', 1)
->with('method', 'images')->get()->toJson();
This doesn't work:
$data = User::find(1)->patients->with('method', 'images')->get()->toJson();
It says:
Call to undefined method Illuminate\Database\Eloquent\Collection::with()
Why is it wrong? Could it be corrected?
The reason your code doesn't work is all Eloquent relationship declaration returns different result depending on whether you are trying to access the relationship as property or as method (with () or without ()).
// Return you chainable queries
$query = User::find(1)->patients()->...
// Return you collection of patients
$patientsCollection = User::find(1)->patients;
Try
User::find(1)->patients()->with('method', 'images')->get()->toJson();
Try this
$patient = New Patient;
$data = $patient->where('user_id','=',1)->with('method','images')->get()->toJson();

Fetching Single Model from Laravel Collection

Let's say you have an Illuminate Collection of User model objects.
$users = User::all();
Now, you want to get a single user from that collection by ID.
The only way I knew of doing this (super ugly):
$user_id = 22;
$user = $users->filter(function($user) use ($user_id) {
return $user->id = $user_id;
})->first();
(Taken from this question and answer.)
However, if you do this, the $users collection is destroyed and unusable. For instance, if there were 100 unique users in the collection before, you will instead now have 100 copies of the user with id 22 for some God forsaken reason.
How can I get a single user by ID from the collection without destroying the collection or looping through it?
I thought this would work...
$user_id = 22;
$temp_users = $users;
$user = $temp_users->filter(function($user) use ($user_id) {
return $user->id = $user_id;
})->first();
But, even more infuriatingly, $users is still destroyed by the filter call - so evidently $temp_users = $users is identical to $temp_users = &$users or something. There appears to be no way of duplicating a collection.
According to this Github issue, Collection::filter() used to return brand new object instances. Evidently, it doesn't anymore. And neither does $temp_users = $users; I guess - which is confusing as hell.
Eloquent responses in the form of collections actually extend a special collection type located at Illuminate\Database\Eloquent\Collection, which has a familiar method find(). Simply use that.
$users = User::all();
$jack = $users->find(22);
In case ID is not your primary key, you could use firstWhere() like this:
$user_id = 22;
$userYouNeed = $users->firstWhere('id', $user_id);
If you would have a more complex condition you can consider using first() and providing your own callback with a condition like this
$user_id = 22;
$userYouNeed = $users->firs(function ($user) use ($user_id) {
return $user->id === $user_id; // Or a more complex condition
});

Categories