I'm working with laravel 4 and the eloquent implementation.
I want to edit/manipulate a value in a database field which contains a json encoded string.
Example: I have a database row with the name "meta". The value of "meta" is a json encoded string.
The example json encoded string:
{"name":"steven","lastname":"builder"}
How can I manipulate the value of that json string?
For example "name" ?
I've found mutators but I dont know how to work with them.
http://laravel.com/docs/eloquent#accessors-and-mutators
This works like most ORM's in that you simply make the change like you would to a normal object's properties, and just save the changes. In this example:
You've already got who you want to update, so we'll just call that object $meta, and you've already manipulated your json, so we'll call it $manip_json, and we'll say the column name is just meta_col
$meta->meta_col = $manip_json;
$meta->save();
Related
I come from a Javascript and Ruby background and this is baffling me. Laravel can store two different array syntaxes in my DB depending on how I handle my array serialization. In my understanding, collect() creates a true Laravel array. Why then is it storing a serialized array? Furthermore, is the {'key':'value'}syntax still an array despite having no square brackets surrounding it? It looks to me like a standard object or a hash, but if I try to do toArray() on it, it recognizes that it's already an array and throws an error. What am I misunderstanding and what is correct here?
Given a form:
edit.blade:
<select class="form-control m-bootstrap-select m_selectpicker" name="temp">
<option value={{ json_encode(array("$key"=>"$cph"), JSON_FORCE_OBJECT) }}>
</select>
The following two controllers syntaxes yield different database insertions.
PageController.php:
$page->cph_default = collect($request->temp);
$page->save();
Laravel stores an array with the following syntax in my database: ["{\"11\":\"1100\"}"]
PageController.php
$page->cph_default = json_decode($request->temp, true);
$page->save();
Laravel stores an array with the following syntax in my database: {"19": "1900"}
A PHP array with the syntax ['key' => 'value'] is called an associative array, and acts like a hash. A JSON-encoded associative array will show up as an object in JSON syntax. Examples and more info on PHP.net
Laravel's collect() function is a convenience wrapper for creating a new Collection. A Collection is not really a "true Laravel array" so much as it is an object wrapper with some convenience methods for modifying the underlying array. Think of it like a scalar object.
In your form when generating the option value, the submitted form value ($request->temp) will be a JSON-encoded string. Literally the string '{"19": "1900"}'.
Calling collect($request->temp) does no modification to that submitted data. It's simply creating a new Collection (array), containing a single string item. If you were to call toArray() on the collection, you'd see something like this:
[
0 => '{"19": "1900"}'
]
Note that this is not an associative array, it is a numeric array with a zero-based index. This array is encoded as a JSON array, not as a hash object. Hence your first result.
Calling json_decode($request->temp) is turning the string back into an associative array (hash) before saving it via Eloquent. Eloquent then calls json_encode() again internally, turning it back into the same JSON as your form's option value.
If you were to decode the form value before creating the collection, the resulting database save would look identical. You'd just have the convenience of the Collection wrapper:
$page->cph_default = collect(json_decode($request->temp, true));
$page->save();
If you're treating the column as a JSON type, you should ensure the data passed to Eloquent is NOT already encoded, or you'll get the double encoding experienced in your first example.
No Matter What is.
First If you are stroring the array into database convert to JSON FORMAT
For eg
$variable = json_encode($request->controlname);
This is the right way to store array
Into database
I'm trying to figure out the best way to convert Object ID's that reference other collections to strings in a set of JSON data. It has to account for nested values. I am using a PHP back end and would like to convert them to strings before returning the data to the React front end.
Our React front end is set up to take the Object ID as a string when crawling through the data to render it, so we need to convert it from an Object ID.
// parentProduct is an ObjectId in the database, linking to a parentProduct collection
// and needs to be converted to a string in PHP when retrieving the JSON data.
{
"_id" : ObjectId("5b87fdb4a767e7c886730dbc"),
"name" : "My Sub-Product",
"parentProduct" : ObjectId("5063114bd386d8fadbd7a003")
}
I have a question and I don't have any idea how to search it or make it.
I have a db for a job portal. In job_requirments column when i add a new row I want to save a list and after display it.
Example:
3 years experience.
etc.
etc.
How can i make to be like an array and display it with a foreach loop? Thx.
You can keep an array as JSON in DB.
From the docs:
The array cast type is particularly useful when working with columns that are stored as serialized JSON. For example, if your database has a JSON or TEXT field type that contains serialized JSON, adding the array cast to that attribute will automatically deserialize the attribute to a PHP array when you access it on your Eloquent model:
protected $casts = [
'job_requirments' => 'array',
];
Once the cast is defined, you may access the options attribute and it will automatically be deserialized from JSON into a PHP array. When you set the value of the options attribute, the given array will automatically be serialized back into JSON for storage
https://laravel.com/docs/5.5/eloquent-mutators#array-and-json-casting
#Alexey Mezenin i realy like your answer and appreciated,
But usually all huge use of implode and explode to perform this
Take a type text of the column in database
Make a comma seperated string of array of values like implode(",",$arr);
And then store it into the database while you want it back simply get that column string and exactly opposite of implode do explode(",",$arr);
it will return you an array of your all saved values
$blog = new blog();
$blog->title = $req->title;
$blog->description = $req->description;
$blog->user_id=$req->user_id;
$blog->save();
return response()->json($blog);
I am using a Yii2 model that is hooked to a PostgresQL database. I have a behavior that encodes and decodes certain attributes of this model to/from json. To encode/decode, I am using the Json helper, the Json::encode and Json::decode methods.
The column in the table is of a json type. An example of what ends up in the database:
"{\"additional_tags\":[\"#здрасте\",\"#кафе\"],\"vk\":\"vk.com\\\/privetik\"}"
When I try to decode it back into a php array, here's what's returned instead:
'{"additional_tags":["#здрасте","#кафе"],"vk":"vk.com\/privetik"}'
EDIT: Come to think of it, the string seems fine, but the behavior of the ::decode method is strange. Essentially, all it does is remove the escape slashes, instead of converting it into a php array or throwing an exception.
What should I do to fix this? Appreciate any feedback.
Looks like the string in your database is encoded twice. Try passing it through Json::decode another time, I bet it will return your array.
I have written a script to query a mysql database and encode the data in json format.
I have added $encoded = json_encode($encodable[0]); which removes the other [ ] brackets but then only displays 1 record. Is there a way to still remove those brackets but display for example every record that I am querying?
Sorry not sure how to describe the problem in a better way!
Encode the result set of the query as JSON? Or encode data that is being sent to the database??
$encodeable[0] is the first element of the array, so its clear that that is what will be encoded. Depending on the format of your data, encodeable[0] would be [{"key":"value"},{"key":"value"},{"key":"value"}] by default as thats an indexed array with keys of 0,1,2...
If your goal is to just output the json as a JS object {}, instead of an array [] you can use json_encode($array, JSON_FORCE_OBJECT); which will encode indexed arrays as {"0":"value"} or {"0":{"0":"value"}} instead of just ["value"] or [["value"]]. If that's not what you're after, you may just need to loop through each encodeable element of your array and encode that way (use a for loop)
http://php.net/manual/en/function.json-encode.php