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();
Related
I have a key value pair that I am inserting into a model with the following:
public function addContactDetail(Request $request){
$data = $request->all();
$contact_id = $data['contact_id'];
$contact = Contact::find($contact_id);
$details = $contact->details;
$details[$data['label']] = $data['value'];
$contact->details = $details;
$contact->save();
return response()->json($contact);
}
After insert it sometimes puts it randomly in the middle of the object. How do I keep it at the end?
If you are using Laravel 5 or greater version,
Try casting your json column into array in eloquent using mutators. like this.
inside your Contact Model
protected $casts = [
'details' => 'array',
];
By doing so, I guess you will get what you want. Try it and let me know
in my db structure
service_request type enum('towel','tissue','napkin')
then have a model
* #property string $service_request
then in my view
<?= $form->field($model, 'service_request')->checkBoxList([ 'towel' => 'Towel', 'tissue' => 'Tissue', 'napkin' => 'Napkin']) ?>
then when i choose towel, tissue and napkin then submit the form, it's have an error said
Service Request must be String
please help me
Thank You
Like Joji Thomas said, checkBoxList prodices an array.
You need to change your database structure so that it supports 1-to-many relations (each $model can have multiple service_requests) if you want to save this. Unfortunately Yii is not very good at this sort of thing out of the box so you have to do a bunch of things yourself.
First you need to create a ServiceRequest ActiveRecord.
Then your $model needs to have a relation like:
public function getServiceRequests() {
return $this->hasMany(ServiceRequest::className(), ['model_id' => 'id'];
}
Then in your controller (model create action) you will need to do something like this:
foreach (Yii::$app->request->post('ServiceRequest',[]) as $data) {
$item = new ServiceRequest($data);
$model->link('serviceRequests', $item);
}
If you wanna update the checkboxes too then you need to do something similar in your model update action as well.
Please change checkBoxList to radioList, because when selecting multiple values service_request becomes an array. Enum type can handle only string values.
First change your filed datatype from enum to varchar. enum only takes a single string value.
Secondly you need to implode service_request array to string for save to db.
Use bellow code before the model save function :
$model->service_request = implode("," , $model->service_request);
$model->save();
So, I have a JSON field in my database. When I access it on my model object, I get a string, so I have to decode it myself. Is it possible to access it like an object? I could define an accessor, but in that case I wouldn't be able to change it.
You can use the Attribute Casting.
Let's assume that in your User model you have an options attribute of type Json so what you can do is adding in your User Model:
protected $casts = [
'options' => 'array',
];
And simply if you want to edit this field you can just do it like so :
$user = App\User::find(1);
$options = $user->options;
$options['key'] = 'value';
$user->options = $options;
$user->save();
Is there anyone who knows how to do this without the technique of doing it in a one query string. I mean the popular ways I see on the net is by looping in data(the updates) and generating a single update statement and then fire a query. Is it possible for an Eloquent Approach or DB without looping?
This is posible with Eloquent, it might be necessary to enable mass-assignment, but you will get an error if so.
$post_data = Input::all();
$model = Model::find($id);
$model ->fill($post_data);
$model ->save();
or
$post_data = Input::all();
Model::find($id)->update($post_data);
Yes, you can do that but in that case, you have to make the array of data that is a loop is needed to store the data in the array with respective field_name => value of the table.
The following is the example:
$Array = array(); //This is needed to hold data while looping over $YourData
$YourData - is the array of data you want to store in the respective table.
foreach ($YourData as $YourDatakey => $YourDatavalue ){
$Array = [
'table_column_name' => $YourDatavalue['value_from_array'],
'table_column_name' => $YourDatavalue['value_from_array'],
'table_column_name' => $YourDatavalue['value_from_array'],
...... and so on
];
}
$InsertQuery= YourModelName::create($Array);
PS:
YourModelName model file should have the columns in protected
$fillable = ['column1','column2'....];
You should use App\Models\ModelName; at the top of the file.
I am trying to extract some data from an array with the following syntax:
#entries_from_db = XrEntry.find(:all, :conditions => [:FeedURI => uri ], :select => 'json')
The :FeedURI is the record that contains an array with uri's ["123456", "23345", "4453"]
The uri is the variable wich contains the current uri.
The statement I'm trying to make is 'select JSON from XrEntry where FeedURI contains uri'
Im stuck on the part to access the array and always get several error msg's when I'm trying different code.
Does anyone has an idea?
Thanks!
I solved it with this syntax
#entries_from_db = XrEntry.find(:all, :conditions => ["FeedURI like ?", "%#{uri}%"] , :select => 'json')
the "%#{your_rails_variable}%" is needed to read in an array
You seem to have switched the condition syntax. you chould start with the db attribute and then the variable.
#entries_from_db = XrEntry.find(:all,
:conditions => { :uri => FeedURI },
:select => 'json')
That will return an array of XrEntry objects with only the json attribute present. To get an array of only the json data you could map it like this:
#json_array = #entries_from_db.map(&:json)