Reputation: 59
I want to access the name attribute from the practice table but I am getting Collections. My code looks like.
$practice = Practice::withTrashed()->where('id',$appointment->practice_id)->get();
dd($practice);
and result looks like
Collection {#697
#items: array:1 [
0 => Practice {#698
#dates: array:1 [
0 => "deleted_at"
]
#fillable: array:2 [
0 => "name"
1 => "email"
]
#connection: null
#table: null
#primaryKey: "id"
#keyType: "int"
#perPage: 15
+incrementing: true
+timestamps: true
#attributes: array:7 [
"id" => 42
"name" => "DJ and Charlie Eye Associates"
"email" => "[email protected]"
"created_at" => "0000-00-00 00:00:00"
"updated_at" => "2017-01-13 06:29:14"
"liferay_id" => 57238
"deleted_at" => "2017-01-13 06:29:14"
]
#original: array:7 [
"id" => 42
"name" => "DJ and Charlie Eye Associates"
"email" => "[email protected]"
"created_at" => "0000-00-00 00:00:00"
"updated_at" => "2017-01-13 06:29:14"
"liferay_id" => 57238
"deleted_at" => "2017-01-13 06:29:14"
]
#relations: []
#hidden: []
#visible: []
#appends: []
#guarded: array:1 [
0 => "*"
]
#dateFormat: null
#casts: []
#touches: []
#observables: []
#with: []
#morphClass: null
+exists: true
+wasRecentlyCreated: false
#forceDeleting: false
}
]
}
Is there any way to do , so I can get the name "DJ and Charlie Eye Associates". I used withThrashed method because this entry is soft deleted in the practice table.
Upvotes: 1
Views: 92
Reputation: 31
Use find()
if id
is the primary key, you will get just the Practice back.
$practice = Practice::withTrashed()->find($appointment->practice_id);
https://laravel.com/docs/5.3/eloquent#retrieving-single-models
Upvotes: 0
Reputation: 819
You can Either use foreach loop
foreach($collection as $collect){
dd($collect->name);
}
or you can just convert the collection into array
$array = $collection->toArray();
dd($array[0]->name);
or
$collection->first()->name;
Hope This Helps You.
Ask if any query
Upvotes: 2
Reputation: 4135
$practice = Practice::withTrashed()->where('id',$appointment->practice_id)->get()->get('name');
dd($practice);
Though this is incredibly ugly and you probably read up on Collections: your statement is doing exactly what Laravel says it does.
https://laravel.com/docs/5.3/collections
Upvotes: 1
Reputation: 163758
First you need to get an object from a collection and then you can get any property of that object:
$practice->first()->name;
Or:
$practice[0]->name;
Upvotes: 2
Reputation: 34914
You could simply get this by using this
dd($practice[0]->name);
Or if you know that your query will return only one object you could use ->first()
in place of ->get()
and then you could use.
dd($practice->name);
->first()
gives first object
->get()
gives array of objects.
Upvotes: 1