Laravel access values from object in object - arrays

In one of the controller function
$readings = Reading::orderBy('reading_date_time', 'DESC')->get();
dd($readings);
This gives
Illuminate\Database\Eloquent\Collection {#1883
#items: array:160 [
0 => App\Reading {#1722
#fillable: array:6 [ …6]
#connection: "mysql"
#table: "readings"
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:8 [ …8]
#original: array:8 [ …8]
#changes: []
#casts: []
#dates: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: []
#touches: []
+timestamps: true
#hidden: []
#visible: []
#guarded: array:1 [ …1]
}...
How can I access the actual values of readings table. And use them for operations like array_column().

This function already give you the result, and the result is collection.
You can call the attribute by single object in collection:
$readings->first()->reading_date_time;
and you can use method-pluck to get the attribute values from collection, it just like array_column:
$readings->pluck('reading_date_time');
If you use array_column, you can use method-toArray to change collection to array:
array_column($readings->toArray(), 'reading_date_time')

You may use toArray() helper
The toArray method converts the collection into a plain PHP array. If
the collection's values are Eloquent models, the models will also be
converted to arrays
$readings = Reading::orderBy('reading_date_time', 'DESC')->get()->toArray();
/*
[
['column1' => 'value1', 'column2' => 'value2', ...],
['column1' => 'value1', 'column2' => 'value2', ...],
['column1' => 'value1', 'column2' => 'value2', ...],
...
]
*/
Then you may use array_column() on $readings array
$pluckedValues = array_column($readings, 'chosen_column');
print_r($pluckedValues);

Related

Loop through a collection of Arrays and return named key value pairs (Laravel/Eloquent)

I am working with Laravel and currently I have an eloquent Collection being returned with 3 arrays within the collection. Within each array are nested Model collections.
The structure is like so:
Illuminate\Database\Eloquent\Collection {#1905 ▼
#items: array:3 [▼
0 => app\Models\User {#1804 ▶}
1 => app\Models\User {#1805 ▶}
2 => app\Models\User {#1806 ▶}
]
}
Each user is like so when expanded
#attributes: array:3 [▼
"user_id" => 12345
"first_name" => "John"
"last_name" => "Doe"]
What I want to have returned is an array with just the user_id => 12345 for all the users.
I tried the traditional foreach but the index keep returning as 0 => 12345 instead of user_id as my key. I also tried pluck() to pull the user_id but I got the same result of a numeric key.
Is there an efficient way to achieve this using eloquent?
Pluck would not work since user_id is the value from the collection you are extracting.
Why not just do a select with only the fields you want...Instead of removing things from collection you don't need?
For example this would return an array of arrays with a key id and value being that id.
User::select('id')->get()->toArray();
[
[
"id" => 1,
],
[
"id" => 2,
],
]
But to do what you want given the data you have you could use map and return only the key-value data you need. Here is a short example:
$collection = [
[
"user_id" => 12345,
"first_name" => "John",
"last_name" => "Doe",
],
[
"user_id" => 12346,
"first_name" => "John 2",
"last_name" => "Doe",
],
[
"user_id" => 12347,
"first_name" => "John 3",
"last_name" => "Doe",
],
];
collect($collection)->map(function ($user) {
return [
"user_id" => $user["user_id"],
];
});
Keep in mind this way from an start array so in your case I am assuming you be doing like:
User::get()->map(function ($user) {
return [
'user_id' => $user->user_id,
];
});

Laravel - Access relations property

I need to access at the email value; it become from a relation hasOnce(),
this is dd($this->order_details)
Illuminate\Database\Eloquent\Collection {#2322 ▼ #items: array:1 [▼
0 => App\Order {#2327 ▼
#hidden: array:1 [▶]
#connection: "mysql"
#table: "orders"
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:12 [▶]
#original: array:12 [▶]
#changes: []
#casts: []
#classCastCache: []
#dates: array:1 [▶]
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: array:1 [▼
"user" => App\User {#2356 ▼
#dispatchesEvents: array:1 [▶]
#fillable: array:3 [▶]
#hidden: array:9 [▶]
#casts: array:1 [▶]
#connection: "mysql"
#table: "users"
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:20 [▼
"id" => 36
"email" => "email#gmail.com"
"password" => "$2y$10$f.u7MO6ZZ4GBf1uaabiF9OXerh0SR7JzUV9M5PGI1IG1xFATkeTSG"
"name" => "NAME"
"surname" => "SURNAME"
"phone" => "+39331199222"
"confirm_code" => 111111
"confirm_code_date" => "2020-06-01 18:17:42"
"confirm_tries" => 0
"city_id" => 5662
"stripe_customer_id" => "cus_HPVN1YJE0wjHtm"
"status" => "ACTIVE"
"is_admin" => 1
"price_list_id" => 1
"wallet" => 99852.6
"last_login_at" => "2020-06-05 11:49:32"
"remember_token" => null
"created_at" => "2020-06-01 18:17:42"
"updated_at" => "2020-06-08 16:33:12"
"deleted_at" => null
when i try to get it with: $this->order_details->user->email
i get back:
Property [user] does not exist on this collection instance.
I've no idea which is my error and what is wrong to get it as well,
with $this->order_details->user[0]->email
the result is the same
You are trying to access an object which is not present in the collection.
$this->order_details is a Collection
You need to access the first order, before you can access the user:
$firstOrder = $this->order_details->first();
$user = $firstOrder->user;
$email = $user->email;
// Or:
$email = $this->order_details->first()->user->email;
Of course you can also iterate over the orders in the collection, but for now I assumed you only need the first order.

Laravel Multidimensional Array to Collection Object Values

I have an array that I'm wanting to recursively turn into a collection and to use the collection as object values.
I would like to use the collection object in similar ways that eloquent is used rather than using $contact['name'] and being able to use $collection->contacts->each vs foreach $collection->contacts .....)
$collection->contacts->each(function ($contact) {
// ability to use $contact->name (and not have to use $contact['name'])
});
Collection Macro:
Collection::macro('recursive', function () {
return $this->map(function ($value) {
if (is_array($value)) {
return (object)$value;
}
if (is_object($value)) {
return collect($value)->recursive();
}
return $value;
});
});
Example:
public function test_it_can_recursively_convert_array_to_collection()
{
$data = [
[
'name' => 'Michael Scott',
'emails' => [
'mscott#dundermifflin.com',
'michaelscarn#dundermifflin.com',
],
'contacts' => [
[
'name' => 'Dwight Schrute',
'emails' => [
'dschrute#dundermifflin.com',
],
],
[
'name' => 'Jim Halpert',
'emails' => [
'jhalpert#dundermifflin.com',
],
],
],
],
];
$collection = collect($data)->recursive();
$this->assertInstanceOf(Collection::class, $collection);
$collection->each(function ($item) {
$this->assertEquals('Michael Scott', $item->name);
$item->contacts->each(function ($contact) {
$this->assertNotNull($contact->name);
});
});
}
The original collection map works (e.g. $collection->each .... $item->name) but I can't seem to set convert the nested arrays to objects and get the object values.
Error: Call to a member function each() on array
Illuminate\Support\Collection^ {#632
#items: array:1 [
0 => {#13
+"name": "Michael Scott"
+"emails": array:2 [
0 => "mscott#dundermifflin.com"
1 => "michaelscarn#dundermifflin.com"
]
+"contacts": array:2 [
0 => array:2 [
"name" => "Dwight Schrute"
"emails" => array:1 [
0 => "dschrute#dundermifflin.com"
]
]
1 => array:2 [
"name" => "Jim Halpert"
"emails" => array:1 [
0 => "jhalpert#dundermifflin.com"
]
]
]
}
]
}

Can't loop through laravel collection array

stuck on collection array
I am getting the specfic array. but can't loop throught in blade
this is my controller:
public function appliedJob($id)
{
$apllied = AplliedJob::with('user','job')->find($id);
return view('dashboardviews.page.apllied-job',compact('apllied'));
}
this my model:
class AplliedJob extends Model
{
use Notifiable;
protected $fillable = [
'name', 'email', 'message','aplied_cv',
];
protected $table='appllied_jobs';
//protected $primaryKey = 'user_id';
protected $primaryKey = 'user_id';
public function user()
{
return $this->belongsTo('App\User','user_id');
}
public function job()
{
return $this->belongsTo('App\Job','job_id');
}
}
this the array I am getting I want to access relation# [job] but it
throws an error
AplliedJob {#257 ▼
#fillable: array:4 [▶]
#table: "appllied_jobs"
#primaryKey: "user_id"
#connection: "mysql"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:9 [▶]
#original: array:9 [▶]
#changes: []
#casts: []
#dates: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: array:2 [▼
"user" => User {#263 ▼
#fillable: array:4 [▶]
#table: "users"
#hidden: array:2 [▶]
#casts: array:1 [▶]
#connection: "mysql"
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:9 [▶]
#original: array:9 [▶]
#changes: []
#dates: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: []
#touches: []
+timestamps: true
#visible: []
#guarded: array:1 [▶]
#rememberTokenName: "remember_token"
}
"job" => Job {#261 ▼
#fillable: array:4 [▶]
#table: "jobs"
#connection: "mysql"
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:10 [▼
"id" => 1
"user_id" => 2
"jb_name" => "web developer"
"jb_type" => "software"
"jb_salary" => "12000"
"jb_exp" => "12"
"jb_description" => "djghnbjkguyfgykgvkvbuykgbkub g uiygjghpiu p;"
"jb_loc" => "lahore"
"created_at" => "2019-05-15 01:18:46"
"updated_at" => "2019-05-15 01:18:46"
]
#original: array:10 [▶]
#changes: []
#casts: []
#dates: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: []
#touches: []
+timestamps: true
#hidden: []
#visible: []
#guarded: array:1 [▶]
}
]
#touches: []
+timestamps: true
#hidden: []
#visible: []
#guarded: array:1 [▶]
}
i have tried this but it gives an exception
#foreach($apllied as $aplil)
{{$aplil->job->jb_name}}
#endforeach
this the error I am getting and can't figure out what am I doing wrong
ErrorException (E_ERROR)
Trying to get property 'job' of non-object (View:
D:\xampp\htdocs\locojobs\resources\views\dashboardviews\page\apllied-
job.blade.php)
find() return one model so you need to do this:
{{$apllied ->job->jb_name}} //Remove the loop
or use get() instead of find()
What i get from this code, each AplliedJob instance has one Job. So as #Anas Bakro says, you need the remove #foreach from your code. If you want to build different architecture please write down your tables.
Try to use get() or paginate() instead of find(), because the find() returns single value.
Try the below code,
public function appliedJob($id)
{
$apllied = AplliedJob::with('user')->with('job')->get();
return view('dashboardviews.page.apllied-job',compact('apllied'));
}

Printing out values of a collection in laravel

In my controller I have
$all = \App\Product::where('campaign_id', $product->campaign_id)->get();
When I DD out in the template
{{ dd($all)}}
I get a collection object
Collection {#340 ▼
#items: array:1 [▼
0 => Product {#341 ▼
#connection: "mysql"
#table: null
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:10 [▶]
#original: array:10 [▶]
#casts: []
#dates: []
#dateFormat: null
#appends: []
#events: []
#observables: []
#relations: []
#touches: []
+timestamps: true
#hidden: []
#visible: []
#fillable: []
#guarded: array:1 [▶]
}
]
}
How do I see the basic array returned?
I know this question is old, but can't believe is not answered.
You need to convert the eloquent model to an array, to display it
{{ dd($all->toArray()) }}
More info here: https://laravel.com/docs/5.6/eloquent-serialization

Resources