Reputation: 355
I have the following Query that returns an array
$wines = Wine::all();
//Remove type_id and producer_id
foreach ($wines as $wine) {
$location = $wine->producer->location;
}
This is what I get if i echo $wine->producer->location;
{"city": "Kavadartsi", "address": "29-ти Ноември, бр. 5, Kavadartsi 1430", "country": "Macedonia"}
So the only property that I need from this is the address which I try to access with
$wine->producer->location->address;
But when I do so I get the following error
Trying to get property 'address' of non-object
If I change the code to
$wine->producer->location['address'];
The error is:
Illegal string offset 'address'
Upvotes: 0
Views: 35
Reputation: 1045
Remove the arrow after location: $wine->producer->location['address'];
If you are getting the same error and if location is in JSON format in your database, json_decode it:
$location = json_decode($wine->producer->location, true);
$address = $location['address'];
Upvotes: 0
Reputation: 510
First of this is wrong: $wine->producer->location->['address'];
, you might want to do this instead $wine->producer->location['address'];
.
If that doesn't work, then it would help a lot to see what your producer migration file looks like, but if am to guess it is probably in json like $table->json('location');
.
If this is the case then you may want to type cast that particular field like this:
<?php
class Location extends Model
{
/**
* The attributes that should be cast.
*
* @var array
*/
protected $casts = [
'location' => 'array',
];
}
After you've done this you can now get your data like this:
$wine->producer->location['address'];
Upvotes: 1