Advil
Advil

Reputation: 33

Laravel get latest username

I'm trying to get te latest username of my users and show that in stats, but id doesn't work.

I'm using laravel.

My code:

$users = DB::table('user')->select('username')->get();

I get an error;

ErrorException (E_UNKNOWN) Array to string conversion (View: C:\xampp\htdocs\CubicCMS_new\system\app\views\layouts\master.blade.php) (View: C:\xampp\htdocs\CubicCMS_new\system\app\views\layouts\master.blade.php)

But i don't see the array to string conversion?

Can someone help me please?

Upvotes: 1

Views: 113

Answers (2)

Advil
Advil

Reputation: 33

The answer to my question is completed!

DB::table('user')->orderBy('id', 'desc')->pluck('username');

Was the solution. Thanks to Joer Hinz

Upvotes: 0

Joel Hinz
Joel Hinz

Reputation: 25414

You're essentially asking Laravel for the usernames of all users. What you want is pluck, and probably also to sort by id in reverse. Like this:

DB::table('user')->orderBy('id', 'desc')->pluck('username');

Also, it's a best practice to name the table users, because it's one table that consists of many users, not one table that consists of one user. But of course, that's up to you entirely. :)

Edit: Having read the question again, I'm wondering if perhaps you do want all usernames after all. In that case, a standard loop should work, i.e.

@foreach ($users as $user)
    {{ $user->username }}
@endforeach

And if it doesn't, please post your code so we can have a closer look!

Upvotes: 4

Related Questions