laravel-translatable: converting existing text column to translatable - mysql

i'm trying to convert and existing text column to translatable. I find that when i add the column name to the the protected translatable array i am no longer able to access it as i did before ($model->key)
I assume that this is because its looked for a translation but can't find one. Is there a way for me to return to contents of the column? I want to retrieve the text and and replace it with a json
when I log $this i can see my object and the correct key: value pairs. Any attempt to access it or convert it to array causes the value to disappear completely
$array = json_decode(json_encode($this), true);
$object = json_decode(json_encode($this), false);
error_log('$this '.print_r($this,true)); // includes the key 'myKey' with correct value
error_log('$array '.print_r($array['mykey'],true)); // empty
error_log('$object '.print_r($object->mykey,true)); // empty

You can use this method if you want to get all translated values of a particular column as an array.
public function update(ModelName $modelItem)
{
return $modelItem->getTranslations('column_name');
}
//result
[
'en' => 'test',
'tr' => 'deneme',
]
Resource:
https://github.com/spatie/laravel-translatable#getting-all-translations-in-one-go

if you want to get the content that still not store as json translation, you can use this eloquent method.
$model->getRawOriginal('your translation's column name');
it will get your column value.

Related

Updating Data within a unique randomly generated ID/KEY in firebase using HTML

function updateFirebase(){
const fb=firebase.database().ref()
//get field values
author = document.getElementById('uname').value
user_email = document.getElementById('umail').value
data = {author, user_email}
//update database
fb.child('Article/').update(data);
}
</script>
I have problem with my code. I want to update the data inside a table named "Article". Article has generated items with a unique key/id and each key has its own content. Lets say I want to be able to edit the "author" or change the "title", the problem is they each have a randomly generated key/id that I cant access. for example that "-LS39kReBHrKGqNj7h_". I can only save the data inside the "Article" tree but I cant change the "author" or the "title". How do i get a workaround this so I can change those properties?
Here is how my firebase looks like
It depends whether you have the record reference on the frontend before update or not (whether you have fetched it before you are trying to update it).
But generally, you have two options
You can store the key reference as an "id" field on the object.
To achieve that, you need two step process when creating the record at the first place
// Creates a new record in DB and returns it to you. Now you can get the "key"
const newRecord = firebase.database().ref('TABLE_NAME_REF').push();
newRecord.set({
id: newRecord.key
...
});
This is great if you fetch the list of records on the frontend and then you want to update one of them. Then you can just build the ref path like this
fb.child('Article/' + record.id ).update(data); // where record is the prefetched thing
You need to find the element based on its fields first. And once you have it, you can update it right away.
To achieve this, you can simply do something like:
firebase.database()
.ref('TABLE_NAME_REF') // let's say 'Article'
.orderByChild('RECORD_KEY') // Let's say 'author'
.equalTo('KEY_VALUE') // let's say 'zoranm'
.limitToFirst(1)
.once("value")
.then(res => {
// You need to loop, it always returns an array
res.forEach(record => {
console.log(record.key); // Here you get access to the "key"
fb.child('Article/' + record.key ).update(data); // This is your code pasted here
})
})

Validaing Multiple, Specific Form Fields with errors()

I am building a multi-step form input (a "wizard") where the user input parts of an entity over multiple form input views. At each step, I want to validate only the input data (not the entire entity).
My question is how to use error() with an array of field names.
The model has 12 fields with validation rules. I want to validate 3 of those in one controller action.
So, in this controller action, I get three inputs
$thedata = $this->request->data;
This results in:
['number' => '102','color' => 'blue','size' => 'large']
I then make an array of field names:
$thearray = array_keys($thedata);
This results in:
[
(int) 0 => 'number',
(int) 1 => 'color',
(int) 2 => 'size']
Now I would like to check these three fields for errors.
$errors = $this->Items->newEntity($this->request->data)->errors($thearray);
This results in checking ALL 12 fields with validation defined, not just the three in the array, and it fails validation (it picks up all the errors in the entity).
If I define only ONE field to check it works:
$errors = $this->Items->newEntity($this->request->data)->errors('number');
This correctly validates only the field 'number' and produces the desired result.
However, passing an array of fields instead of a string with a single field name validates ALL fields requiring validation.
Also, I tried hard-coding an array as a parameter of errors():
$errors = $this->Items->newEntity($this->request->data)->errors(['number','color']);
That also checks all 12 fields in the table definition, not just these two.
So the question is, how do you prepare the array and pass it to the errors() method if you want to check only two or three specific fields?
Thanks in advance for any advice!
D
Thanks in
According to the docs errors can take a $field argument, but not an array. If you want to validate multiple fields without validating all of them, you could loop over $thearray.
$item = $this->Items->newEntity($this->request->data);
foreach ($thearray as $error) {
$errors[] = $item->errors($error);
}

Pass data from JSON to variable for comparison

I have a request that I make in an API using GET
LWP::UserAgent,
the data is returned as JSON, with up to two results at most as follows:
{
"status":1,
"time":1507891855,
"response":{
"prices":{
"nome1\u2122":{
"preco1":1111,
"preco2":1585,
"preco3":1099
},
"nome2":{
"preco1":519,
"preco2":731,
"preco3":491
}
}
}
}
Dump:
$VAR1 = {
'status' => 1,
'time' => 1507891855,
'response' => {
'prices' => {
'nome1' => {
'preco1' => 1111,
'preco3' => 1099,
'preco2' => 1585
},
'nome2' => {
'preco3' => 491,
'preco1' => 519,
'preco2' => 731
}
}
}
};
What I would like to do is:
Take this data and save it in a variable to make a comparison using if with another variable that already has the name stored. The comparison would be with name1 / name2 and if it is true with the other variable it would get preco2 and preco3 to print everything
My biggest problem in the case is that some of these names in JSON contain characters like (TradeMark) that comes as \u2122 (some cases are other characters), so I can not make the comparison with the name of the other variable that is already with the correct name
nome1™
If I could only save the JSON already "converted" the characters would help me with the rest.
Basically after doing the request for the API I want to save the contents in a variable already converting all \u2122 to their respective character (this is the part that I do not know how to do in Perl) and then using another variable to compare them names are equal to show the price
Thanks for the help and any questions please tell me that I try to explain again in another way.
If I understand correctly, you need to get the JSON that you receive in UTF8 format to an internal variable that you can process. For that, you may use JSON::XS:
use utf8;
use JSON::XS;
my $name = "nome1™";
my $var1 = decode_json $utf8_encoded_json_text;
# Compare with name in $name
if( defined $var1->{'response'}->{'prices'}->{$name} ) {
# Do something with the name that matches
my $match = $var1->{'response'}->{'prices'}->{$name};
print $match->{'preco1'}, "\n";
}
Make sure you tell the Perl interpreter that your source is in UTF8 by specifying use utf8; at the beginning of the script. Then make sure you are editing the script with an editor that supports that format.
The function decode_json will return a ref to the converted value. In this case a hash ref. From there you work your way into the JSON.
If you know $name is going to be in the JSON you may omit the defined part. Otherwise, the defined clause will tell you whether the hash value is there. One you know, you may do something with it. If the hash values are a single word with no special characters, you may use $var1->{response}->{prices}->{$name}, but it is always safer to use $var1->{'response'}->{'prices'}->{$name}. Perl gets a bit ugly handling hash refs...
By the way, in JSON::XS you will also find the encode_json function to do the opposite and also an object oriented interface.

How to check if JSON response fields are alphabetically sorted?

How to validate the JSON Response fields? After validating the fields I need to check whether the fields are alphabetically sorted or not. How would I do it ?
The JSON object is unordered set of name/value pairs. There is no guarangee of ordering at all. You need to take json object keys list and sort them. After sorting access to object fields by sorted keys list.
If you mean how to check list (array) of values. You need to implement simple loop through array and check that each element must be less than next element in sorting comparision criteria.
For js language checking array for alpha ordering may be done like this:
var array = ["Apple", "Application", "AppName", "Happy"];
var isSortedAlpha = array.reduce(function(res, current, index, arr) {
return res && arr[index&&index-1] <= current
}, true);

JSON - look up values in array

With the following json
{
"Count":0,
"Message":{
"AppId":0
},
"Data":"[{\"application_name\": \"Grand Central\",\"feature_name\": \"1 Click Fix\",\"access_type_id\": 2,\"member_name\": \"GC_Remote_Support_Security\"},{\"application_name\": \"Grand Central\",\"feature_name\": \"Account Details\",\"access_type_id\": 2,\"member_name\": \"GC_Remote_Support_Security\"},{\"application_name\": \"Grand Central\",\"feature_name\": \"Account Summary\",\"access_type_id\": 2,\"member_name\": \"GC_Remote_Support_Security\"}]"
}
how do I go through the Data array, in the most succinct coding manner possible, to see if any feature_name matches a given string?
Since your JSON contains nested, quoted JSON, you will need nested deserializations using LINQ to JSON to parse your Data array. Having done so, you can use use SelectTokens to query with a JSONPath query to find nested properties named feature_name, then check their value:
var testString = "Account Summary";
var found = JToken.Parse(JObject.Parse(jsonString)["Data"].ToString()).SelectTokens("..feature_name").Any(t => (string)t == testString);
Debug.Assert(found == true); // No assert.
Update
If you want the all JObject with a "feature_name" property matching a given value, you can do:
var foundItems = JToken.Parse(JObject.Parse(jsonString)["Data"].ToString())
.SelectTokens("..feature_name")
.Where(t => (string)t == testString)
.Select(t => t.Ancestors().OfType<JObject>().First()) // Get the immediate parent JObject of the matching value
.ToList();