user4315864
user4315864

Reputation:

How to use laravel Eloquent to take just one field?

I am new in Laravel and I am watching a video tutorial that is teaching Laravel 3, unfortunately Laravel 4 is very different with laravel 3 and I don't know why? and I am afraid that maybe laravel 5 will be so different with laravel 4.

I am going to select all data about one field from my users table:

    $user=new user;
    $username=$user::find(1)->username;
    return $username;

The top code is working true but just return the username of a user that it's id is equal to 1, But I want to do something like below:

$user=new user;
$username=$user::all()->username;
return $username;

This code has error $user::all()->username; and the error is :

Undefined property: Illuminate\Database\Eloquent\Collection::$username

Upvotes: 0

Views: 233

Answers (1)

lukasgeiter
lukasgeiter

Reputation: 152900

You can use the lists() function, described here
It will return an array with all the values of one property.

(Also you don't need to create an instance to retrieve all users)

$usernames = User::lists('username');

If you'd like to have another column as key of your array (e.g. the id) do this:

$usernames = User::lists('username', 'id');

Don't be worried about Laravel 5. Some things will change but many things will stay the same. Including everything about Eloquent and the DB querying in general (at least as far as I know)

Upvotes: 1

Related Questions