Murlidhar Fichadia
Murlidhar Fichadia

Reputation: 2609

Two column values in same table Laravel 5.4 merge into Array

I want to merge example_1 and example_2 values into array.

example_1 and example_2 are of type int.

User::select('example_1','example_2')->where('id',Auth::user()->id)->get();
// The result: [{"example_1":"1","example_2":"2"}]

example_1 and example_2 if has value 1 and 2 respectively.

I want to have an array : [1,2]

Upvotes: 0

Views: 702

Answers (2)

Sandeesh
Sandeesh

Reputation: 11906

You can do one of this

$result = array_only(auth()->user()->toArray(), ['example_1','example_2']);

// Or

$result = User::where('id', auth()->id())->first(['example_1','example_2'])->toArray();

// Finally

$data = array_values($result);

Upvotes: 2

TheAlexLichter
TheAlexLichter

Reputation: 7289

All Eloquent queries return Collection objects. Those can be modified easier (through collections methods).

You can use first() to get the first object out of this collection.

Now you can access the variables of the Eloquent User model by calling them like you'd call public class properties.


Your final code would look like:

$user = User::select('example_1','example_2')
          ->where('id',Auth::user()->id)->get()->first();

$array = [ $user->example_1, $user->example_2 ]; 
// The result: [1,2]

Upvotes: 0

Related Questions