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.





you put sum this apply to array you return one object
– Alexander Villalobos
Aug 31 at 17:37


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

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Edmonton

Crossroads (UK TV series)