How can I decrement the value of population
in cycles table by using the value of number_of_mortality in mortalities
table to subtract the population?
For example
The have 2 data in cycles table
Id 1 - (Date range from September 3 to September 28) Population = 3000
Id 2 - (Date range from October 1 to November 5) Population = 9000
I user wants to put a number of mortality to cycle id 1 , so he/she go to mortality modal.
The user inputs the date and it belongs to the cycle id 1 date range. The value of number_of_mortality is 25. After the user inputs the data, he/she click the add to submit to database.
After the submit, The value of population of cycle id 1 will be decrease and it should be 8975 ( 9000 - 25 = 8975).
This is my controller
MortalityController.php (store)
public function store(Request $request)
{
$this->validate($request, array(
'date_input' => 'required|date',
'number_of_mortality' => 'required|numeric',
));
$cycle = Cycle::select('id', 'date_start_raise')
->where('date_start_raise','<=',$request->get('date_input'))
->where('date_end_raise','>=',$request->get('date_input'))
->get();
$id = 0;
$chickenAge = 0;
$input= Carbon::parse($request->get('date_input'));
foreach($cycle as $value){
$id = $value->id;
}
if ($id) {
$start = Carbon::parse($value->date_start_raise);
$chickenAge = $start->diffInDays($input) ;
}
return Mortality::create([
'date_input' => request('date_input'),
'number_of_mortality' => request('number_of_mortality'),
'chicken_age' => $chickenAge,
'cause_of_death' => request('cause_of_death'),
'cycle_id' => $id,
'user_id' => Auth::id()
]);
}
I figured how to connect the mortalities
table to cycles
table by using dates but I don’t know how and where can I put the code in decrementing by using the number_of_mortality to subtract the population. Can you help me? Thanks
MortalityController.php (update)
public function update(Request $request, $id)
{
$mortality = Mortality::findOrFail($id);
//validate
$this->validate($request, array(
'date_input' => 'required|date',
'number_of_mortality' => 'required|numeric',
) );
$mortality->update($request->all());
}
MortalityController.php (Destroy)
public function destroy($id)
{
$mortality = Mortality::findOrFail($id);
$mortality->delete();
}