如何在laravel中获取列表的第一个元素?

时间:2014-03-24 15:33:58

标签: php laravel laravel-4

我的问题并不困难:)我使用 Laravel 4 ,我只想获得列表的第一个元素,我的代码是:

public function index()
{
    $userid = User::lists('id'); // here i want to get the first element of my list
    $services = User::find($userid)->service;
    $username = User::lists('username');

    return View::make('services.index',array('services'=> $services,'username'=>$username));
}

所以如果有人有任何想法,我将非常感激:)

3 个答案:

答案 0 :(得分:2)

在Laravel中,'lists'方法返回一个数组。因此,您可以使用以下内容访问数组中的第一个对象:

$userid[0] = $firstUserId;

答案 1 :(得分:1)

如果您不需要列表,只需要第一项:

$user = User::first();

$userid = $user->id
$services = $user->service;
$username = $user->username;

答案 2 :(得分:0)

获取第一个项目/实例

$user = User::first();
//or
$user = User::find(1); //by id
//or
$user = User::findOrFail(1); //it will throw an error

$user_id = $user->id;
$service = $user->service;
$username = $user->username;