Basaa Basaa - 6 months ago 11
MySQL Question

Eloquent - Get specific columns from logged-in user

In Laravel

$user = Auth::user()
returns the currently logged in user. From this user I want to retrieve only a few columns into a key-value array. What are my options?

Example:

$user = Auth::user()->fetch('id', 'username', 'email');


should give me

[
"id" => 1,
"username" => "John Doe",
"email" => "john@doe.example"
]


I've searched the Eloquent documentation, but haven't found the function I'm looking for. Have I missed it? Does such a function not exist?

Answer

Auth::user() fetches a user object for you, so you are no longer in Eloquent and can't use Eloquent methods.

There's no method on a model that returns an array of given attributes (reference: https://laravel.com/api/5.2/Illuminate/Database/Eloquent/Model.html), but you can make one on your User model, for instance like this:

function myData($keys) {
    return array_intersect_key($this->toArray(), array_flip($keys))
}

Then you can call it using $user->myData(['id', 'username', 'keys'])