this might be a different question from the questions that has been asked here already about inserting arrays into the database, but mine is quite different.
Here's the code:
public function something(Request $request)
{
$id = $request ->id;
$name = $request->name;
$money = $request ->money;
$data = array(
'name' => $name,
'money' => $money,
);
$z = User::where('id',$id)
->select('name','money')
->first();
$data2 = array(
'name' => $z->name,
'money' => $z->money,
);
$diff = array_diff($data,$data2);
$diff_name = array_keys($diff);
$diff_values = array_values($diff);
for ($i = 0; $i < count($diff_name); $i++) {
$z->$diff_name[$i] = $diff_values[$i];
$z->save();
}
return 'Success';
}
Model:
class User extends Model
{
protected $table = 'users';
protected $fillable = ['name','money'];
public $timestamps = false;
}
$data:
array(2) { ["name"]=> string(9) "Somewhere" ["money"]=> string(7) "5123.00"}
$data2:
array(2) { ["name"]=> string(8) "Anywhere" ["money"]=> string(7) "5000.00"}
So I'm using array_diff to determine if the values that has been entered by the user is equal from the original value from the database, if theres a difference in value then get the column name($diff_name) and then insert the new value($diff_value).
I did it this way since I will be needing the values of $diff_name for history log purposes.
However I'm getting this error Array to string conversion
Thanks in advance.
$dataarray look like? Can youvar_dump()it and add to your question as well? I am thinking that those values are actually arrays and not strings.