如何在laravel中添加从数据库中获取的数组数据的限制

如何在laravel中添加从数据库中获取的数组数据的限制

问题描述:

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?

我正在从用户表中检索行,我正在使用下面的代码。
p>

 &lt;?php $ user = User :: get();  ?&gt; 
  code>  pre> 
 
 

我想为$ user数据添加数组限制。 我不想使用 paginate(); code>。 添加限制我使用下面的代码,但它不起作用

$ users = array_slice($ users,0,2); code>

\ n但它显示如下错误消息 p>

异常'ErrorException',消息'array_slice()期望 参数1为数组,对象给出'在...中 ... p> blockquote>

如何为 $ user code>添加限制? p> div>

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

try limit or

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

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

In recent Laravel versions you can also use:

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

Note that User model must extend Eloquent.

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