I have a table, table name is bookings and here have a column e_provider. this column i direct fetch data by id and save all data in e_provider field how can i access this e_provider data like $data->e_provider->name
here is code
[
{
"id": 2,
"e_provider": "{"id":11,"name":"Architect O'Reilly, Ratke and Miller","phone_number":"661.425.3559","mobile_number":"307.607.7472"}",
}
]
CodePudding user response:
in laravel 8 and less try this
Defining A Mutator
public function getEProviderAttribute(){
return json_decode($this->getAttributeValue('e_provider'));
}
https://laravel.com/docs/8.x/eloquent-mutators#defining-a-mutator
CodePudding user response:
You can use $casts in your model
class BookingModel extends Model
{
protected $casts = [
'e_provider' => AsCollection::class,
];
}
Now you will be able to get the data by the following:
$bookingModel->e_provider->id
https://laravel.com/docs/9.x/eloquent-mutators#array-object-and-collection-casting
Another way if you don't want to use casts, you can define an accessor:
protected function eProvider(): Attribute
{
return Attribute::make(
get: fn ($value) => collect(json_decode($value)),
);
}
https://laravel.com/docs/9.x/eloquent-mutators#defining-an-accessor