laravel 如何在laravel中获取列表的第一个元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22613817/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to get the first element of a list in laravel?
提问by user3438415
My problem is not difficult :) i use Laravel 4, and i just want to get the first element of my list, my code is :
我的问题不难:) 我使用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));
}
so if someonehas any idea i will be very appreciative :)
所以如果有人有任何想法,我会非常感激:)
回答by seeARMS
Within Laravel, the 'lists' method returns an array. So, you may simply access the first object in the array by using something like:
在 Laravel 中,'lists' 方法返回一个数组。因此,您可以简单地使用以下内容访问数组中的第一个对象:
$userid[0] = $firstUserId;
回答by marcanuy
If you don't need the list but just the first item:
如果您不需要列表而只需要第一项:
$user = User::first();
$userid = $user->id
$services = $user->service;
$username = $user->username;