If exists: update, else: insert in Laravel 5.5 [duplicate]
If exists: update, else: insert in Laravel 5.5 [duplicate]
This question already has an answer here:
I'm trying to figure it out if my if else in my controller is right. It works and doesn't produce an error but the update doesn't work. Even though it exists, its still add a new one
public function store(Request $request)
$collection = Collection::create([
'assignment_id' => $request->input('assignment_id'),
'bag_id' => $request->input('bag_id'),
'weight' => $request->input('weight')
]);
$station = Collection::join('assignments', 'collections.assignment_id', '=', 'assignments.id')
->join('stations', 'assignments.station_id', '=', 'stations.id')
->select('stations.id')
->where('collections.id', '=', $collection->id)
->first();
$weight = Collection::join('assignments', 'collections.assignment_id', '=', 'assignments.id')
->join('stations', 'assignments.station_id', '=', 'stations.id')
->select('collections.weight')
->where('collections.id', '=', $collection->id)
->first();
//query in selectings process that exists within a month
$processexist = Process::select('*')
->where('bag_id', $request->input('bag_id'))
->whereMonth('created_at', date('m'))
->first();
if($processexist == null)//if doesn't exist: create
$processes = Process::create([
'bag_id' => $request->input('bag_id'),
'station_id' => $station->id,
'total_weight' => $weight->weight
]);
else //if exist: update
$processes = Process::where('id', $processexist->id)
->update(['weight'=>sum($weight->weight)]);
return redirect('/collections');
In my store in CollectionsController, everytime I add a collection, a process would be added. If the process exist, it'll only update the weight, but it doesn't, it would add a new one. Like I said, it doesn't update if it is exist but it would a new one. I hope you can help me figuring it out. Thanks!
This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.
sum
object
2 Answers
2
you cant try this if you want to sum
$processes = Process::where('id', $processexist->id)->first();
$processes->weight += $weight->weight;
$processes->save();
If exist will return it else create one (Already save at DB)
$process = Process::findOrCreate(array $attributes, array $values = );
If exist will return it else instanciate a new one (Wont save at DB);
$process = Process::findOrNew(array $attributes, array $values = );
And
Process::updateOrCreate(array $attributes, array $values = )
https://laravel.com/api/5.5/Illuminate/Database/Eloquent/Builder.html#method_findOrNew
you put
sum
this apply to array you return oneobject
– Alexander Villalobos
Aug 31 at 17:37