Laravel Eloquent is adding double quotes around data insert - mysql

When creating a new record, I am trying to fill in a field which is LONGTEXT. I use it to store json data.
$newRecord = new Profile([
'info' => '[]',
]);
$newRecord->save();
In the database, the data is being stored as "[]" (with quotes around the data entered) instead of [] which is breaking logic in my application. How can I make sure it enters the data correctly? Also, I have tried setting [] as default value for the LONGTEXT column but MySQL returns an error saying it's not allowed for LONGTEXT columns.

Figured it out. 'info' column in this case is casted as an array in the Profile Model:
protected $casts = [
'info' => 'array',
];
Using an empty array [] rather than '[]' as a String fixed the issue:
$newRecord = new Profile([
'info' => [],
]);

Related

Laravel get JSON array from database

What is the best way in Laravel to store an array in your database? And how do I get the same array with a query?
I have a variable that's an array in an array:
$colors = array(array('green'), array('yellow', 'white'));
When I store $colors, my database (column type = json) save it as:
[["green"], ["yellow", "white"]]
But when I try to get it from a query, I couldn't get the same array as $colors.
My query:
$colors = DB::table('colors')
->where('id', '1')
->value('arraycolors');
I hope someone can help how to query an array. Thanks a lot!
You don't need to convert the array data to a JSON string yourself, use the Laravel $casts parameter on your model: https://laravel.com/docs/9.x/eloquent-mutators#array-and-json-casting
You should do something like this in your model:
protected $casts = [
'colors' => 'array',
];
And I recommend changing your migration to text instead of json column like so:
$table->text('colors')->nullable();

Issues trying to access an associative array converted from JSON in Laravel

I'm working on a Laravel project that implements react-jsonschema-form and I need to convert the values saved in the database to an associative array so I can pluck certain values from it. However I am getting strange results when doing so.
Here is the code I use to grab the JSON data from the table and then convert to an array:
$form = Form::where('id', $formId)->get();
$converted = json_decode($form[0]->form_data, true);
$formArray = print_r($converted, 1);
return $formArray;
For testing purposes I am simply rendering the data in the browser.
The result from the above return is:
Array
(
[1] => Array
(
[1.1] => New
[1.2] => Ms
[1.3] => Isobel Fleming
[1.4] => Array
(
[uprn] => 52375918
[address_1] => Fake Street
[address_2] =>
[address_3] =>
[town_city] => BRISTOL
[postcode] => BS1 3KE
)
[1.5] => 0129711011
[1.6] => 0800999111
[1.7] => 0781100022
[1.8] => isobelfleming#jourrapide.com
)
)
which is great. However when I try and access anything from it like:
return $formData[1][1.1]
I get:
String offset cast occurred
If I try using a string:
return $formData[1]['1.1']
I get:
Illegal string offset '1.1'
So I am not sure what to do to access this data. The problem is, although it's not ideal to have the associate keys with decimals in them, this is the way the schema is set up and it's several thousand lines long - this is just a snippet of the form data.
Is there anything that can be done in order to get the data from this array?
I figured it out. It seems like the following line was the problem:
print_r($converted, 1);
It didn't need to be printed as an array, I should have just used the $converted variable to access the data like so:
return $converted[1]['1.1'];

Symfony 2 / Doctrine Not Saving Any Zeros in varchar field

UPDATE
As asked for,
$NewUser = new Users();
$Form = $this->createForm(new UserType(), $NewUser, [])
->add('save', 'submit', ['label' => 'Save',
'attr' => ['class' => 'SaveButton ftLeft'],
]);
$Form->handleRequest($request);
if ($Form->isValid()) {
/*
Sometimes add more data to the entity.....
*/
$em = $this->getDoctrine()->getManager();
$em->persist( $NewUser );
$em->flush();
}
$FormRender = $Form->createView();
return $this->render('xxxxBundle:Users/add.html.twig',
['AddUser' => $FormRender]);
Sometimes I will add extra to the entity, on fields being set within the php code, e.g. account sign up date, but in most cases just save the entity with the form data.
Very simple issue, I have a new (ish) system and have notice that when trying to save zeros, for anything, phone number inputs, it does not save any zeros?
I am using YMAL files to control my doctrine ORM, here is how I have set it up within my User table,
mobileNumber:
type: string
nullable: false
length: 50
options:
fixed: false
column: mobile_number
This does save/make the field has a varchar, and thought nothing about it until I did a random test and saw it was not saving any leading zeros?
I know you can not save leading zeros in a int field type, but this is a varchar. Also when I go into the database, and manually add a zero to that input, its fine, so I take its not the database. Something to do with how I get doctrine to save the data?
If so how do I change that? I have just been saving the data with a standard persist() and flush() commands? Not sure why it would not save the zeros? I was thinking that I had to change the YMAL type to something like phone? I have been over the docs, can not see it.
All help most welcome..
Thanks.
The reason is in your comment:
User form type has the mobile number set to 'number' input.
This value is being casted to int by the Form component. Change the field type to regular string.
If you want to validate value to be only digits, use Validation component

Inserting JSON to DB Using Model in Laravel

I'm trying to use the model create option and this is my array:
$result = array(
'match_id' => $input['id'],
'score' => $input['score'],
'result' => $input['result'],
'headline' => NULL,
'article' => $input['report'],
'tries' => $input['try'],
'try_amount' => $input['tryquant'],
'conversions' => $input['conv'],
'conv_amount' => $input['convquant'],
'penalties' => $input['pens'],
'pen_amount' => $input['penquant'],
'dropgoals' => $input['dgs'],
'dg_amount' => $input['dgquant']
);
Result::create($result);
The contents of some of these are arrays themselves. eg:
$input['penquant'] = [
"4"
]
When I run my code, it saves the data to the DB simply as Array and throws up the following error:
ErrorException in helpers.php line 703: preg_replace(): Parameter mismatch, pattern is a string while replacement is an array
Can someone tell me what I'm doing wrong and how to fix it?
Shouldn't have rushed, forgot to use json_encode.
The best is to use mutators and accessors in your model.
example of mutator
// convert pen_amount from snake case to studly case
// The set...attribute (the ... is you field name which is in studly case) helps transform the data before you save it
// into the database
public function setPenAmountAttribute($value)
{
$this->attributes['pen_amount'] = serialize($value);
}
example of an accessor is
// convert pen_amount from snake case to studly case
// the get...Attribute (the ... is you field name which is in studly case) helps you convert the data back to it original state
public function getPenAmountAttribute($value)
{
return unserialize($value);
}
You can use accessors and mutators for all your fields that you want to save as array. This is elegant. No need to manually use json_encode and decode in your controllers.

Yii2: Prevent empty string in attribute of ActiverRecord

What's the best way to prevent that an empty string gets inserted into a field of an MySQL's InnoDB table? Allowed values are strings with more than zero characters or NULL.
I'm asking that because ActiveRecord model objects often get loaded with view's form data which don't know and thus don't send NULL values. In such a case I'd prefer that a NULL gets stored instead of the empty string.
Should I define a rule? Should I implement a setter? Use a trigger?
You should simply use the default validator, add this rule to your model :
public function rules()
{
return [
// ...
['attribute', 'default', 'value' => null],
// ...
];
}