Laravel 5.4 doesn't convert empty string to null - laravel-5.4

Laravel 5.4 doesn't convert empty string like "" to null.
For Example when I create a route like this
Route::get('/string/trim' , function(){
dd(request()->input('email'));
});
and call this url:
http://example.com/string/trim?email=
I see empty string in output not null value.
In the app/Http/Kernel.php file these lines of codes are also existed:
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
];

TrimStrings are only for form elements, not for router query params.

Related

laravel-translatable: converting existing text column to translatable

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.

Vuejs changes order of json_encoded array, when decodes it back from props in vuejs component

Php:
$json_string = "{
"26":{"blabla":123,"group_id":1,"from":"27.08.2018","to":"02.09.2018"},
"25":{"blabla":124,"group_id":1,"from":"20.08.2018","to":"26.08.2018"},
"24":{"blabla":125,"group_id":1,"from":"20.08.2018","to":"26.08.2018"}
}"
my.blade.php template:
<my-component :records={{ $json_string }}></my-component>
MyComponent.vue:
export default {
props: ['records'],
...
mounted: function () {
console.log(this.records);
}
Output is:
{__ob__: Observer}
24:(...)
25:(...)
26:(...)
And when I use v-for, records in my table in wrong order (like in console.log output).
What I am doing wrong?
EDIT:
I figured out 1 thing:
When I do json_encode on collection where indexes are from 0 till x, than json string is: [{some data}, {some data}]
But if I do ->get()->keyBy('id') (laravel) and than json_encode, json string is:
{ "26":{some data}, "25":{some data}, "24":{some data} }
Then how I understood, issue is in different outer brackets.
In Javascript keys of objects have no order. If you need a specific order then use arrays.
Here is documentation for keyBy Laravel method: https://laravel.com/docs/5.6/collections#method-keyby
I wanted to have ids for rows data to fast and easy access without iterating over all rows and check if there is somewhere key Id which is equals with my particular Id.
Solution: not to use keyBy method in Laravel and pass json string to Vue component like following [{some data}, {some data}] (as I described in my Question Edit section) - this will remain array order as it used to be.
I found this short and elegant way how to do this, instead of writing js function by myself:
Its find() method: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find
Example:
let row = records.find( record => record.id === idToFind );

Django MySQL Query Json field

I have a MySQL database with a table containing a JSON field called things. The JSON looks like this
things = {"value1": "phil", "value2": "jill"}
I have collection of objects that I have pulled from the database via
my_things = Name_table.objects.values
Now, I'd like to filter the my_things collection by one of the JSON fields. I've tried this
my_things =
my_things.filter(things__contains={'value': 'phil'})
which returned an empty collection. I've also tried
my_things = my_things.filter(things={'value': 'phil'})
and
my_things = my_things.filter(things__exact={'value': 'phil'})
I'n using Django 1.10 and MySQL 5.7
Thoughts?
It depends on how exactly do you store JSON in field. If you use django-jsonfield, then your things will be string without spaces, with strings inside of quotation marks: '{"value1":"phil","value2":"jill"}'.
Then, via docs:
my_things = my_things.filter(things__contains='"value1":"phil"')
should return your filtered QuerySet, because
>>> tmp_str = '{"value1":"phil","value2":"jill"}'
>>> '"value1":"phil"' in tmp_str
True

How to convert JSON Array String to Set in java

I have a JSON Array string like [1,2].I want to convert this in to Set.How can I do it in java 8 ?
This is my code
String languageStr = rs.getString("languages");
jobseeker.setLanguageIds(StringUtils.isEmpty(languageStr) ? null
: Arrays.stream(languageStr.split(","))
.map(Integer::parseInt)
.collect(Collectors.toSet()));
Getting error like this
java.lang.NumberFormatException: For input string: " 2"
The space in json array is the problem.Is there any solution?
This is my code after changes
String languageStr = rs.getString("languages");
String languages=languageStr.substring(1,languageStr.length()-1);
jobseeker.setLanguageIds(StringUtils.isEmpty(languages) ? null
: Arrays.stream(languages.split(","))
.map(String::trim)
.map(Integer::parseInt)
.collect(Collectors.toSet()));
Can I get the output in any other way withot using these 2 steps:
languages=languageStr.substring(1,languageStr.length()-1);
.map(String::trim)
You can use the trim method to remove leading and trailing withespace before parse it to Integer.
So your code will be this
Arrays.stream(languageStr.split(","))
.map(String::trim)
.map(Integer::parseInt)
Finally I got the solution
Changed code like this:
String languageStr = rs.getString("languages");
Set<Integer> languages = mapper.readValue(languageStr, typeFactory.constructCollectionType(Set.class, Integer.class));
jobseeker.setLanguageIds(StringUtils.isEmpty(languageStr) ? null : languages);
Using a TypeToken and the Google Gson library, you should be able to do that like below:
String languageJsonStr = rs.getString("languages");
Set<Integer> myLanguageSet = new Gson().fromJson(languageJsonStr, new TypeToken<HashSet<Integer>>(){}.getType());

Checking the first element of json

I am very new to Json and need to access elements of json:
$users=User::all()->toJson();
print_r($users[0]) gives only [
and print_r($users[0]->email) gives me the error trying to get property of non object.
$users[0]["email"] gives Illegal string offset 'email'.
$users[0].email Use of undefined constant name - assumed 'email'
How do i get the name of first user?
it acts like a string so it shows only [ while $user[0].. don't use toJson()
$users = User::all();
$email = $users[0]->email;
is enough. to get the value from the array.