0

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!

boldsinas101
  • 300
  • 2
  • 5
  • 22

2 Answers2

2

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

Danon
  • 2,771
  • 27
  • 37
1

you cant try this if you want to sum

 $processes = Process::where('id', $processexist->id)->first();
 $processes->weight += $weight->weight;
 $processes->save();