How to subtract two integer values from different tables - php

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();
}

You can use the decrement() method.
After successfully creating the mortality you can decrement the population in the cycle:
Store:
public function store(Request $request)
{
$this->validate($request, array(
'date_input' => 'required|date',
'number_of_mortality' => 'required|numeric',
));
// Make sure you only get the correct cycle here
$cycle = Cycle::where('date_start_raise', '<=', $request->get('date_input'))
->where('date_end_raise', '>=', $request->get('date_input'))
->first();
$chickenAge = 0;
$input= Carbon::parse($request->get('date_input'));
if ($cycle) {
$start = Carbon::parse($cycle->date_start_raise);
$chickenAge = $start->diffInDays($input) ;
}
$mortality = 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' => $cycle->id ?? 0,
'user_id' => Auth::id()
]);
// decrement population after successfully creating the mortality
if ($cycle) {
$cycle->decrement('population', $mortality->number_of_mortality);
}
return mortality;
}
Update:
public function update(Request $request, $id)
{
$this->validate($request, array(
'date_input' => 'required|date',
'number_of_mortality' => 'required|numeric',
));
$mortality = Mortality::findOrFail($id);
$oldNumberOfMortality = $mortality->number_of_mortality;
// fill the model with the new attributes
$mortality->fill($request->all());
// check if number_of_mortality was changed
if ($mortality->isDirty('number_of_mortality')) {
$cycle = $mortality->cycle;
$difference = $oldNumberOfMortality - $mortality->number_of_mortality;
// check if the difference is positive or negative and increment or decrement
if ($difference < 0) {
$cycle->decrement('population', abs($difference));
} elseif ($difference > 0) {
$cycle->increment('population', $difference);
}
}
$mortality->save();
return mortality;
}

Related

Laravel UPDATE query with multiple where conditions not working

I am fed up. Simple update method not working. It should update record matching the given item_id,restaurant_id and avil_date.
public function updateWeeklyItem(){
$item_id=request('item_id');
$restaurant_id=request('restaurant_id');
$avil_date=request('avil_date');
weekly_item::where(function($query) use ($item_id, $restaurant_id,$avil_date){
$query->where('item_id', $item_id)
->where('restaurant_id', $restaurant_id)
>where('avil_date', $avil_date);
})->update ([
'start_time'=>request('start_time'),
'end_time'=>request('end_time'),
'tiffin-switch'=>request('tiffin-switch'),
'lunch-switch'=>request('lunch-switch'),
'snacks-switch'=>request('snacks-switch'),
'dinner-switch'=>request('dinner-switch'),
'special-switch'=>request('special-switch'),
'extend-avil'=>request('extend-avil'),
'unit'=>request('unit'),
'quantity'=>request('quantity')
]);
}
Use This Code:
public function updateWeeklyItem(Request $request) {
$item_id = $request->item_id;
$restaurant_id = $request->restaurant_id;
$avil_date = $request->avil_date;
$item = weekly_item::where(function($query) use ($item_id, $restaurant_id,$avil_date) {
$query->where('item_id', $item_id)
->where('restaurant_id', $restaurant_id)
->where('avil_date', $avil_date);
})->first();
$item_array = (
'start_time' => $request->start_time,
'end_time' => $request->end_time,
'tiffin-switch' => $request->tiffin-switch,
'lunch-switch' => $request->lunch-switch,
'snacks-switch' => $request->snacks-switch,
'dinner-switch' => $request->dinner-switch,
'special-switch' => $request->special-switch,
'extend-avil' => $request->extend-avil,
'unit' => $request->unit,
'quantity' => $request->quantity
);
$item->update($item_array);
return $item;
}

How to add elements to array in for loop, PHP - Laravel

I'm connecting to 3 databases which are stored in array $firmy
For now they are hard coded into array but they will be set via Axios request.
public function show(Request $request, $division, $id)
{
$firmy = array('connection1', 'connection2', 'connection3');
$data = [];
foreach ($firmy as $firma) {
DB::setDefaultConnection($firma);
$calendar = new CalendarEvent();
$data[] = CalendarEventResource::collection($calendar->with('calendarCategories')->where('start', '>', '2020-05-21')->get());
DB::purge($firma);
}
foreach ($data as $firma_event) {
foreach ($firma_event as $event) {
$eventT[] = $event;
}
}
return $eventT;
}
I set the connection, get collection and close the connection.
3 times in this case.
Then I loop through the data to get all records in one go.
Here's the API response returned by $eventT array:
[{"id":17549,"title":"Test","description":"test","contact":"test","email":"test","cat":1,"approved":0,"kto_dodal":450,"calendarCategories":{"id":1,"name":"Ogolna","color":"blue"},"start":"2020-09-30","end":"2020-09-30","private":0,"created_at":null,"updated_at":null},
{"id":17580,"title":"Test","description":"test","contact":"test","email":"test","cat":1,"approved":0,"kto_dodal":450,"calendarCategories":{"id":1,"name":"Ogolna","color":"blue"},"start":"2020-09-30","end":"2020-09-30","private":0,"created_at":null,"updated_at":null},
{"id":17545,"title":"Test","description":"test","contact":"test","email":"test","cat":1,"approved":0,"kto_dodal":450,"calendarCategories":{"id":1,"name":"Ogolna","color":"blue"},"start":"2020-09-30","end":"2020-09-30","private":0,"created_at":null,"updated_at":null}]
One per each connection/table which is fine.
I would like to add a name of the connection to each record. So the API response would look like this:
{"id":17545,"title":"Test","description":"test","contact":"test","email":"test","cat":1,"approved":0,"kto_dodal":450,"calendarCategories":{"id":1,"name":"Ogolna","color":"blue"},"start":"2020-09-30","end":"2020-09-30","private":0,"created_at":null,"updated_at":null, "firma":connection1}]
So "firma":nameOfConnection added to each record.
I tried looping through the data[] and using array_push but I can't place the value of connection inside each record.
Value ends up outside of object:
0: {id: 17549, title: "Test", description: "Test ",…} 1: {firma: "connection1"} firma: "connection1"
I managed to sort it.
First I added a value of firma to Resource class so it gets added to collection although it will be null because there is no column in DB with that name:
public function toArray($request)
{
return [
'id' => $this->id,
'title' => $this->title,
'description' => $this->description,
'contact' => $this->contact,
'email' => $this->email,
'cat' => $this->cat,
'approved' => $this->approved,
'kto_dodal' => $this->kto_dodal,
'calendarCategories' => new CalendarCategoryResource($this->whenLoaded('calendarCategories')),
'start' => $this->start,
'end' => $this->end,
'private' => $this->private,
'created_at' => $this->created_at,
'updated_at' => $this->updated_at,
'firma' => $this->firma,
];
}
Then I access Event collection,loop through the results and set value of firma to whatever value the loop is currently at.
public function show(Request $request, $division, $id)
{
$firmy = array('connection1', 'connection2', 'connection3');
$data = [];
foreach ($firmy as $firma) {
DB::setDefaultConnection($firma);
$calendar = new CalendarEvent();
$data = CalendarEventResource::collection($calendar->with('calendarCategories')
->where('start', '>', '2020-09-21')
->where('private', '=', '0')
->get());
// Loop over data in collection and set value of firma
foreach ($data as $value) {
$value->firma = $firma;
$total[] = $value;
}
DB::purge($firma);
}
return $total;
}
Here's the returned value with the attribute firma inside the object:
{"id":17545,"title":"Test","description":"test","contact":"test","email":"test","cat":1,"approved":0,"kto_dodal":450,"calendarCategories":{"id":1,"name":"Ogolna","color":"blue"},"start":"2020-09-30","end":"2020-09-30","private":0,"created_at":null,"updated_at":null,"firma":"connection1"},

How to save a variable based on the a different variable?

I'm trying to mark exam "is_complete" if the "result" reaches 2. I would like to do this when the form is submitted by the user after completing the test and calculating the results. Both variables are in the same table. Is this possible through PHP or do I need to use Java script.
Here is how I've tried to work out the code.
On the model
public function answers()
{
return $this->hasMany('App\ExamResultsAnswers');
}
public function passed()
{
$instance = new ExamResult;
$instance->result < 2;
$var = ExamResult::where('result', '>=', 2)->get();
$var_is_greater_than_two = ($var >= 2 ? true : false);
$condition = new ExamResult;
$condition->is_complete ='1';
if ($this->compare($instance, $condition)) {
return $instance->$column == 1;
}
}
On the controller
public function exam($course_id, Request $request)
{
$course = Course::where('id', $course_id)->firstOrFail();
$answers = [];
$exam_score = 0;
foreach ($request->get('question') as $question_id => $answer_id) {
$question = ExamQuestion::find($question_id);
$correct_answer = ExamOption::where('exam_question_id', $question_id)
->where('id', $answer_id)
->where('is_correct', 1)->count() > 0;
$answers[] = [
'exam_question_id' => $question_id,
'exam_option_id' => $answer_id,
'corect' => $correct_answer
];
if ($correct_answer) {
$exam_score += $question->score;
}
}
$exam_result = ExamResult::create([
'exam_id' => $course->exam->id,
'employee_id' => \Auth::id(),
'result' => $exam_score,
]);
$exam_result->answers()->createMany($answers);
$exam_result->passed();
return redirect()->route('learn.show', [$course, $request])->with('message', 'Test score: ' . $exam_score);
}
The controller is supposed to do the following
Find all the course and the exam that are associated with the course- this works
Then find all the questions and the options for the questions - this works
Then if the user selects the correct answer
then count all correct answers - this works
Then I want to save the
results and mark it complete if the answers are above a 2 correct
answers. - Here the code saves the exam_id, employee_id and result,
but it doesn't make it complete if the result is equal to 2. That is
why I was trying to do this on the model.
Use the following code to mark the Exam as completed:
$exam_result = ExamResult::create([
'exam_id' => $course->exam->id,
'employee_id' => \Auth::id(),
'result' => $exam_score,
]);
$exam_result->answers()->createMany($answers);
if($exam_result->result > 2) {
$exam_result->is_complete = 1;
$exam_result->save();
}
Let me know if i misunderstood the requirement.
Another optimised solution
$exam_result = ExamResult::create([
'exam_id' => $course->exam->id,
'employee_id' => \Auth::id(),
'result' => $exam_score,
'is_complete' => $exam_score > 2
]);
$exam_result->answers()->createMany($answers);

How to subract integer data using the other table with date condition?

I want to decrement the _remain_overall_quantity from inventory table by using the feed_consumed in consumption table
In condition
if $chickenAge <= 8 The decrement will occur in CBC
if $chickenAge > 8 && $chickenAge <= 20 The decrement will occur in BSC
if $chickenAge > 20 The decrement will occur in BFP
This is my ConsumptionController.php
public function store(Request $request)
{
$this->validate($request, array(
'date_input' => 'required|date',
'feed_consumed' => 'required|numeric',
) );
//declaring values
$chickenAge = 0;
$input= Carbon::parse($request->get('date_input'));
$cycle = Cycle::where('date_of_loading','<=',$input)
->where('date_of_harvest','>=',$input)
->first();
if ($cycle) {
$start = Carbon::parse($cycle->date_of_loading);
$chickenAge = $start->diffInDays($input) ;
}
$inventory = Inventory::where('cycle_id','=',$cycle->id ?? 0)
->first();
$consumption = Consumption::create([
'date_input' => request('date_input'),
'chicken_age' => $chickenAge,
'feed_consumed' => request('feed_consumed'),
'cycle_id' => $cycle->id ?? 0,
'user_id' => Auth::id()
]);
return $consumption;
}
I don't know where can i put the decrement and i don't know what will be the if condition statement. Can you help me?
try adding this code just before you return statement:
if ($chickenAge <= 8)
{
DB::table('inventory')->where('id', 1)->decrement('remain_overall_quantity ', 1); // CBC
}
elseif ($chickenAge <= 20)
{
DB::table('inventory')->where('id', 2)->decrement('remain_overall_quantity ', 1); // BSC
}
else
{
DB::table('inventory')->where('id', 3)->decrement('remain_overall_quantity ', 1); // BFP
}
if you need to decrement by more than 1 then change the "1" in 'remain_overall_quantity ', 1 part
some insight to increment/decrement in Laravel:
https://laravel.com/docs/5.7/queries#increment-and-decrement

Lavachart display count each months

Hello i need serious help cause i have tried all way and not find an answer... so i really want to display chart that count many data each month, ex january 2 data, febuary 3 data etc... pls look at this brother
public function lihatkeluhan(){
$halaman="tindaklayanan";
$keluhan_list=DB::table('keluhans')
->select(DB::raw('id,tanggal,produk,username,area,masalah,status'))->get();
$keluhan_group = keluhan::select(DB::raw('id,tanggal,produk,username,area,masalah,status'))
->get()->groupBy(function($date) {
return Carbon::parse($date->tanggal)->format('m'); // grouping by months
});
foreach ($keluhan_group as $group) {
$count[] = count($group);
}
$bulan = array("Jan","Feb","Mar","Apr","Mei","Jun","Jul","Agu","Sep","Okt","Nov","Des");
$count = Count($keluhan_list);
$population = Lava::DataTable();
$population->addDateColumn("Month")
->addNumberColumn('Keluhan');
foreach($keluhan_group as $group){
$population->addRow(["jan",$count]);
}
Lava::LineChart('Population', $population, [
'title' => 'Tahun : 2017',
'titleTextStyle' => [
'color' => '#212F3C',
'fontSize' => 14
]
]);
$keluhan_group used to group by month
$count result is number of data each month
But idk how to display on chart...
Btw $population->addDateColumn("Month") is not work, it not display month but year T_T
Replace your code from $keluhan_group to $population with below code and check.
here you need to pass array of month and count of that month
$keluhan_group = keluhan::select(DB::raw("COUNT(*) as count , MONTHNAME(created_at) as month"))
->orderBy("created_at")
->groupBy(DB::raw("month(created_at)"))
->get()->toArray();
$chart_array = array();
foreach($keluhan_group as $data){
$n_data = [];
array_push($n_data,$data['month'],$data['count']);
array_push($chart_array,$n_data);
}
$population = Lava::DataTable();
$population->addDateColumn("Month")
->addNumberColumn('Keluhan')
->addRow($chart_array);
hope this will Help.
see i have implemented chart using my 'User' tabel,
i was not having lavachart in my project so i have update it using http://itsolutionstuff.com/post/laravel-5-geo-chart-example-and-demo-using-lavacharts-packageexample.html
here is my controller code:
$users = Users::select(DB::raw("COUNT(*) as count , MONTHNAME(created_at) as month"))
->orderBy("created_at")
->groupBy(DB::raw("month(created_at)"))
->get()->toArray();
$chart_array = array();
foreach($users as $data){
$n_data = [];
array_push($n_data,$data['month'],$data['count']);
array_push($chart_array,$n_data);
}
$lava = new Lavacharts;
$popularity = $lava->DataTable();
$popularity->addStringColumn('Country')
->addNumberColumn('Popularity')
->addRows($chart_array);
$lava->LineChart('demochart', $popularity, [
'title' => 'Demo population count',
'animation' => [
'startup' => true,
'easing' => 'inAndOut'
],
'colors' => ['blue', '#F4C1D8']
]);
return view('welcome', ['lava' => $lava]);
and in my .blade file:
<div id="temps_div"></div>
<?= $lava->render('LineChart', 'demochart' , 'temps_div') ?>
Hope this will Help.
$companies=Company::all();
$start = (new DateTime('2017-01-01'))->modify('first day of this month');
$end = (new DateTime('2022-01-01'))->modify('first day of next month');
$interval = DateInterval::createFromDateString('12 month');
$period = new DatePeriod($start, $interval, $end);
$lava = new Lavacharts; // See note below for Laravel
$finances = \Lava::DataTable();
$finances->addDateColumn('Year');
foreach($companies as $company)
{
$finances ->addNumberColumn($company->company_name." ".$company->company_location." total sales amount");
}
foreach ($period as $dt) {
$yeardate=$dt->format("Y-m-d");
$insertrow = array( $yeardate );
foreach($companies as $company)
{
$cmp= $company->company_name;
$loc= $company->company_location;
$companiesinfo[]=$cmp." ".$loc;
$databasename=$company->database_name;
\Config::set('database.connections.tenant.host', 'localhost');
\Config::set('database.connections.tenant.username','root');
\Config::set('database.connections.tenant.password', '');
\Config::set('database.connections.tenant.database', $databasename);
\Config::set('database.default', 'tenant');
DB::reconnect('tenant');
$calculatesalesofcompany=B2CFINAL::
select(DB::raw('sum(GrandTotal) as total'))
->where(DB::raw('YEAR(SaleDate)'), '=', $yeardate)
->first();
if($calculatesalesofcompany->total==null)
{
$calculatesalesofcompany->total=0;
}
array_push( $insertrow, $calculatesalesofcompany->total );
}
$finances ->addRow($insertrow);
}
\Lava::ComboChart('Finances2', $finances2, [
'title' => 'Company Performance',
'titleTextStyle' => [
'color' => 'rgb(123, 65, 89)',
'fontSize' => 16
],
'legend' => [
'position' => 'in'
],
'seriesType' => 'bars',
]);

Categories