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.
Advertisement
Answer
There is are several built in Eloquent methods that you could implement.
public function something(Request $request) { $z = User::where('id',$request->id) ->select('name','money') ->first(); // You could also use '->firstOrFail()' if you want to stop execution if a model was not retrieved. $z->fill([ 'name' => $request->name, 'money' => $request->money, ]); $diff = array_keys($z->getDirty()); $z->save()' return 'Success'; }
$model->firstOrFail()
Can be used to stop execution to prevent an error from trying to manipulate a model which was not retrieved from the database.
$model->fill()
This can be used to pass an array of values which you would like to update.
$request->only([‘name’,’money])
Instead of passing an array to
$model->fill()
you could have also used this.
$model->getDirty()
After changing a models attributes (and before saving it) you can use this to get an associative array of the attributes and corresponding values which have changed.