Laravel: decode JSON within Eloquent - json

I need to JSON decode a certain column in my Eloquent query. Is there a way to do this without breaking all apart?
So far I have this.
public function index()
{
return Offer::all();
}

Use an accessor on the model:
public function getColumnNameAttribute($value) {
return json_decode($value);
}
or use attribute casting to tell Laravel to do it automatically:
protected $casts = [
'column_name' => 'array',
];
The array cast type is particularly useful when working with columns that are stored as serialized JSON.
Note that you may have to stop json_encodeing your data if you use casts, as Laravel will now do that step automatically as well.

Related

How to convert Laravel DB data into a suitable JSON form to use it in vuejs

The attributes of laravel modal are named using underscore (_), for example :
first_name
but attributes of javascript objects are named with camelCase:
{ firstName: "..." }
And this presents a conflict, is there a solution to resolve it ?
Try to use Laravel eloquent resource pattern will do that for You.
Check this helpful documentation.
https://laravel.com/docs/8.x/eloquent-resources
Like Zrelli Mjdi mentioned it's done with Resource Collections.
I did not find a way to let this resources transform the result recursively for nested JSON-Objects, so I created a middleware (see the github-gist) for this, which should take a rather heavy toll on performance. So use it sparsely.
I'd use this middleware only temporary if your frontend demands camel-case properties. In the long run I'd modify my migrations to use camel-case fieldnames. This should, according to this reddit-thread, be possible and won't affect performance like my middleware.
Edit: The code in the gist had a bug which is now fixed.
This is about how it's done with Resource-Collections and non-nested JSON-Results:
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class MyResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
public function toArray($request)
{
return [
'id' => $this->id,
'userId' => $this->user_id,
'createdAt' => $this->created_at,
];
}
}
in the controller:
public function myControllerMethod(Request $request)
{
// ...
return MyResource::collection($logs)
}

Laravel Relation on Json Array

i have relation b/w product categories and model where in model i have product_categories_id where i will save ["product_categories_id1","product_categories_id2"]
so
i have seen this https://github.com/staudenmeir/eloquent-json-relations
and used like this in Models.php
use \Staudenmeir\EloquentJsonRelations\HasJsonRelationships;
public function category()
{
return $this->belongsToJson(ProductCategory::class, 'product_category_id');
}
but did'nt get the expected result
Define the field type in model and try it. Also please make sure the array should not have the key.
protected $casts = [
'product_category_id' => 'json',
];

Laravel format resource collection response error Property [product_id] does not exist on this collection instance

In laravel we can format our json response from resource class as seen below
class ProductsResource extends JsonResource
{
public function toArray($request)
{
return [
'id'=> $this->product_id ,
'code'=> $this->product_code,
'shortdescription'=> $this->product_short_description,
'image'=> $this->product_image,
];
}
}
But when returning resources collection i can't format my collection error Property [product_id] does not exist on this collection instance
class ProductsResource extends ResourceCollection
{
public function toArray($request)
{
return [
'id'=> $this->product_id ,
'code'=> $this->product_code,
'shortdescription'=> $this->product_short_description,
'image'=> $this->product_image,
];
}
}
thanks.
It's because ResourceCollection expects a collection of items instead of a single item. The collection resource expects you to iterate through the collection and cannot perform single enitity routines directly from $this (as it's a collection).
See resource collections in documentation
What you are probably looking for is to cast a custom mutation which examples can be found here:
See custom casts in documentation
Look/search for Value Object Casting. It is explained thoroughly how to mutate attributes on get and set, which is probably better than a resource collection (if this is the only thing you wish to do with it). This will modify the collection immediately and saves you from having to manually instantiate the resource collection every time you need it (as you are modifying at model level).
Coming from the docs:
Value Object Casting
You are not limited to casting values to primitive types. You may also cast values to objects. Defining custom casts that cast values to objects is very similar to casting to primitive types; however, the set method should return an array of key / value pairs that will be used to set raw, storable values on the model.
But to get back on topic...
If you dump and die: dd($this); you will see there is an attribute called +collection
In case you wish to transform keys or values, you have to iterate through $this->collection in order to transform the collection values or keys to your requirements.
As you can see in the parent class Illuminate\Http\Resources\Json\ResourceCollection the method toArray() is already a mapped collection.
In which you can see it's pointing to $this->collection
/**
* Transform the resource into a JSON array.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
public function toArray($request)
{
return $this->collection->map->toArray($request)->all();
}
You could use something like the following. And update the item/key values within this collection map.
return $this->collection->map(function($item, $key){})->toArray();
if you wish to transform the values before returning it to an array.
Or a simple foreach like this (have not tested it and there are far better ways of doing this) But for the sake of sharing a simple-to-grasp example:
$result = [];
// Map the associations to be modified
$resultMap = [
'product_id' => 'id',
'product_code' => 'code',
'product_short_description' => 'shortdescription',
'product_image' => 'image'
];
// Iterate through the collection
foreach ($this->collection as $index => $item)
foreach ($item as $key => $value)
$result[$index][$resultMap[$key]] = $value;
return $result;

Yii2 how can an model attribute is modified after load method? (like the afterFind method)

I have an attribute of the model which should be modified after it's loaded from the database.
I could extend the afterFind method, which could the convert the varchar value to a php array. So it works find.
But when the model is loaded I have no idea how to convert that varchar to the php array.
I have tried with rules but does not works:
[['languages'], 'each', 'rule' => ['string']],
or this one
[['languages'], 'safe'],
So this one works afterFind:
public function afterFind()
{
$this->languages = $this->convertToPHPArray($this->languages);
parent::afterFind();
}
By the way I have tried to extend the init or the __constructor method with this conversation, but no success, after load method the languages attribute is still a string instead of a php array.
If I understood your question, I think that you could use a property in the model:
public class Model {
public function getLanguagesArray()
{
return $this->convertToPHPArray($this->languages);
}
}
Then, use it:
$arr = $model->languagesArray;

Propel toArray Mechanics in Doctrine?

I was using Propel for a long time and now I want to try Doctrine.
In My Propel days I used PropelObjectCollection::toArray (for a collection) or PropelObject::toArray() for a single record to convert the PropelObject via array to json.
In my company we override the toArray method to store virtual columns in the array and then the json string.
For example:
public function toArray() {
$arr = parent::toArray();
$arr['full_name'] = $this->getFullName(); // full_name isnt part of the table, it's just a getter
return $arr;
}
When I turn this into json i have my full_name property in my json and then in my Extjs store Object (we use extjs).
Now I wanna try doctrine, but doctrine doesn't seem to allow this.
Can i override a function or property in my doctrine class, or can I do this by annotations, is it possible to generate a json with propertys ('first_name', 'last_name', 'full_name') if my Doctrine class only has the properties $first_name, $last_name and no $full_name
or is there a work around to achieve the same?
Thanks for your help
Edit:
I found something in JMSSerializerBundle if you use Annotations:
#VirtualProperty
use JMS\Serializer\Annotation\VirtualProperty;
at the top of my Doctrine Entity File and an example method
/**
*
* #VirtualProperty
* #return string
*/
public function getFullName() {
return $this->getName(). " mylastname";
}
my json then contains the virtual property full_name