0

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?

0

5 Answers 5

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

try limit or

<?php 
    $user = User::get(); 
    $user = $user ->take(10);
?>
Sign up to request clarification or add additional context in comments.

Comments

1

In recent Laravel versions you can also use:

User::limit(10)->offset(0)->get();

Note that User model must extend Eloquent.

2 Comments

This is better answer as it already limits the result from the query so the result is simply what is needed not all users. You can also use ->take(10)->get()
The get method is best, and should be, called after where, limit, offset, and everything for better resource management.
0

Do you mean to use:

$users = array_slice($user, 0,2); 

1 Comment

array_slice would be good if $user is an array. Possibly converting it to an array first would do $users = array_slice($user->toArray(), 0, 2); but a better method would simply be $users = $user->take(2);
0

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);

Comments

0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.