Laravel Array to string conversion error while updating database - laravel

I want to update a totcosty field in the User table but it is throwing this error everytime and it is not updating the field
this is the function for execution:
public static function cost(){
$user = User::find($user_id);
$total = Helper::totcost();
// dd($tot_amt);
$user->totcosty = $total;
$user->save();
}

array to string means you are sending an array to the database but db will not accept it you have to explode() the array before sending it to db...
Hope it will help!

If you really want to store an array in some table field, then better declare it as a JSON field. For this, your DB should have support for JSON type columns.
See here how to do this.
Once this is done, you can save arrays in that column, you can assign an array value to the model property and laravel will convert it to JSON while saving and also it will be converted to array while retrieving.

Related

Laravel Collection Filter breaking serialization format

I have a serialized String like this
$string = '[{"name":"FOO"},{"name":""},{"name":"BAR"}]';
I am trying to process it via Laravel Collection's filter method and eliminate items without a defined "name" property.
$collection = collect(\json_decode($string));
$collection = $collection->filter(function($v){
return !empty($v->name);
});
$string = \json_encode($collection->toArray());
dd($string);
Normally I am expecting something like this:
[{"name":"FOO"},{"name":"BAR"}]
But I'm getting something like this:
{"0":{"name":"FOO"},"2":{"name":"BAR"}}
Funny thing is, if I skip the filtering process or return true every time, I keep getting the string in the desired format. Removing the toArray() call has the same result. I don't want to keep the numeric indices as associative object keys.
Why this anomaly? And what should I do to get the serialized data in desired format?
In PHP arrays the index key must be unique.
In your case you have the key 'name' and collection automatically assigns the index key to all items in the collection.
To overcome that problem just call
$string = \json_encode($collection->values());

bulk insert the Array still Considered as Object NOT DUPLICATE

i try the answer to this about bulk insert in laravel Query builder.
my query output is
[
{"name":"Dayle","id":1,"email":"dayle213#gmail.com"},
{"name":"John","id":2,"email":"john.doe#gmail.com"}
]
but when i try
DB::table('staff')->insert($data);
i get error Query\Builder::insert() must be of the type array, object given,
when i try
DB::table('staff')->insert($data->toArray());
i get error Object of class stdClass could not be converted to string.
how can i insert inn bulk ?
$data is encoded as JSON object, you need to decode it to make an array:
$data = json_decode($x, true); // array
DB::table('staff')->insert($data);

read manipulate and write to the db in Laravel

I am going to read the data by query, manipulate some values and write it back to the db. I use the code below but I get an error.
$data = DB::table('users')->get()->toArray();
foreach ($data as $d){
$d->id = $id+100;
DB::table('users')->insert($d);
}
Argument 1 passed to Illuminate\Database\Query\Builder::insert() must be of the type array,
but the input is already an array. Do you have a better solution for this?
Ok. let's explain this, what ->toArray() actually did is converting the whole collection to array not casting the selected records to array so if you dd($data) you will find it's an array of objects not array of arrays, so what you need to do is to cast each record in the selected records like so
$data = DB::table('users')->get()->map(function ($user) {
return (array) $user;
})->toArray();
as i said
->toArray() - this will convert the whole collection to array
(array) $user - this will convert the selected record to array
you can simply use increment function
DB::table('users')
->increment('id', 100);
more info : laravel docs

Laravel treating decimal as string

Im trying to make the next eloquent query
$result = $result->where('money','>=',(float)$moneyFilter);
The money column in my database its DECIMAL(11,2), when I run the query it returns an empty array, when I go over php artisan tinker and see the column money, it's a string value "11.1".
I would like to filter the $result collection to have values over $moneyFilter.
Thanks
You need to define in your model which fields need to be cast to a primitive attribute.
protected $casts = ['my_decimal' => 'float'];
There is a really good explanation here:
https://mattstauffer.com/blog/laravel-5.0-eloquent-attribute-casting/
Also there is an explanation in the docs:
https://laravel.com/docs/5.5/eloquent-mutators#attribute-casting

Code igniter with data mapper giving in valid json

I have this to select columns from a table and I want to pass this to Jquery ajax fn.
I am using below code but getting invalid json
My table has three column id, name and city but I am not selecting city
This is my json reponse
["{id:1,name\":\"JOHN\",\"city\":\"null\"}"
,"{\"id\":2,\"name\":\"MICHEAL\,\"city\":\"null\"}"]
Sadly the current stable (1.8.1) WanWizard datamapper DMZ_Json class double encode fields when you call all_to_json(). This issue seem to be fixed in the develop branch. You could workaround this multiple ways:
1. Call to_json() on individual model objects and create the json array with string manipulation:
$my_objects = (new Model)->get();
$results = array();
foreach ($my_objects as $o) {
$results[] = $o->to_json();
}
// building a json array from the strings returned by $o->to_json()
print '['.join(',', $results).']';
2. You can use the array extension's all_to_array method and json_encode that result:
$my_object_arrays = (new Model)->get()->all_to_array();
print json_encode($my_object_arrays);

Resources