Input date value and compare with existing table - laravel

I'm trying to develop a program with Laravel. I have created a table ‘tbl_holiday’ like below:
database table
I have created a form containing 02 input (date) types named ‘from_leave’ and ‘to_leave’.
I want to check these 2 inputs value(date) with the database table ‘tbl_holiday’ having the condition:
If the previous day of ‘from_leave’ match with ‘tbl_holiday.holiday_date’
Or next day of ‘to_leave’ match with ‘tbl_holiday.holiday_date’
The message “Invalid”.
Else
Message “Valid”.
Thanks in advance.

You can simply use wherebetween and check the number of data available in the collection.
$from = $request->from_date;
$to = $request->to_date;
$dates = YourModel::whereBetween('holiday_date', [$from, $to])->get();
if($dates->count() == 0){
return "valid";
}else{
return "Invalid";
}

Related

Update a database field with Joomla UpdateObject method with a calculated field from same table

Right to the point.
I need to update a field in the database using the field to calculate the new value first.
E.g of fields: https://i.stack.imgur.com/FADH6.jpg
Now I am using the Joomla updateObject function. my goal is to take the "spent" value from the DB table without using a select statement.
Then I need to calculate a new value with it like (spent + 10.00) and update the field with the new value. Check out the code below:
// Create an object for the record we are going to update.
$object = new stdClass();
// Must be a valid primary key value.
$object->catid = $item['category'];
$object->spent = ($object->spent - $item['total']);
// Update their details in the users table using id as the primary key.
$result = JFactory::getDbo()->updateObject('#__mytable', $object, 'catid');
The bit which i need to make the calculation on is
$object->spent = ($object->spent - $item['total']);
I realise I can use a seperate insert statement but I am wondering if there is a better way. Any help is much appreciated.
It needs to work like this, WITHOUT THE SELECT (working example)
$query = $db->getQuery(true);
$query->select($db->quoteName('spent'));
$query->from($db->quoteName('#__mytable'));
$query->where($db->quoteName('catid')." = ". $item['category']);
// Reset the query using our newly populated query object.
$db->setQuery($query);
$oldspent = $db->loadResult();
// Create an object for the record we are going to update.
$object = new stdClass();
// Must be a valid primary key value.
$object->catid = $item['category'];
$object->spent = ($oldspent - $item['total']);
// Update their details in the users table using id as the primary key.
$result = JFactory::getDbo()->updateObject('#__mytable', $object, 'catid');
The sticking point with trying to use updateObject('#__mytable', $object, 'catid'); is that your query logic needs to reference the column name in the calculation to assign the "difference" as the new value. The raw mysql query syntax to update a column value with the value minus another value is like:
"`spent` = `spent` - {$item['total']}"
updateObject() will convert spent - {$item['total']} to a literal string, the database will expect a numeric value, so UPDATE results in a 0 value recorded. In other words, $db->getAffectedRows() will give you a positive count and there will be no errors generated, but you don't get the desired mathematical action.
The workaround is to discard updateObject() as a tool and build an UPDATE query without objects -- don't worry it's not too convoluted. I'll build in some diagnostics and failure checking, but you can remove whatever parts that you wish.
I have tested the following code to be successful on my localhost:
$db = JFactory::getDBO();
try {
$query = $db->getQuery(true)
->update($db->quoteName('#__mytable'))
->set($db->quoteName("price") . " = " . $db->qn("price") . " - " . (int)$item['total'])
->where($db->quoteName("catid") . " = " . (int)$item['category']);
echo $query->dump(); // see the generated query (but don't show to public)
$db->setQuery($query);
$db->execute();
if ($affrows = $db->getAffectedRows()) {
JFactory::getApplication()->enqueueMessage("Updated. Affected Rows: $affrows", 'success');
} else {
JFactory::getApplication()->enqueueMessage("Logic Error", 'error');
}
} catch (Exception $e) {
JFactory::getApplication()->enqueueMessage("Query Syntax Error: " . $e->getMessage(), 'error'); // never show getMessage() to public
}
Here is a StackOverflow page discussing the mysql subtraction logic: update a column by subtracting a value

How to maintain total column in database

I'm new to laravel. I have one income table in the database and I want to maintain the total amount of users but there is a condition if the same user adds new deal_price then all the column will be updated except total and total will be updated like old deal_price+new deal_price.
this my controller
public function storeincome(Request $request){
$date=$request->get('date');
$parse_date=Carbon::parse($date)->format(' d-m-y H:i');
$party_name = $request->Input('party_name');
$deal_price = $request->Input('deal_price');
$mode = $request->Input('mode');
$slug = Str::slug($party_name, '');
$total = $request->Input('deal_price');
$data = array('date'=>$parse_date,'party_name'=>$party_name,'deal_price'=>$deal_price,'mode'=>$mode,'party_slug'=>$slug,'total'=>$total);
Income::insert($data);
return redirect(route('admin.dashboard'))->with('success', trans('message.success.create'));
}
this my table colums
Thanks.
Just update other columns normally and while updating the column 'total', fetch the value of deal_price(old) from your database and store it in a variable ($old_deal_price).
Now, just add the old_deal_price ($old_deal_price) and new_deal_price ($request->deal_price) and update that value in your 'total' field.
$total = ($old_deal_price) + ($request->deal_price);
Goodluck!

Query builder where between custom date format

My field date (varchar datatype) is in a custom date format it's dd-mm-yyyy.
Example : 01-01-2016
I want to get data between specific dates from a database field date. Let's say input data are stored in variables: startDate & endDate.
I tried with this query but the result are weird.
$query = DB::table('test')->whereBetween('date', array($startDate, $endDate))->get();
I think it fails because I used a custom date format.
How can this be solved?
#updated
let's say i have date like this
29-12-2015
29-12-2015
29-12-2015
30-12-2015
29-12-2015
01-01-2016
06-01-2016
i set $startDate & $endDate like this
$startDate = "01-12-2015";
$endDate = "01-01-2016";
it's even not get any result with this script
$query = DB::table('test')->whereBetween('date', array($startDate, $endDate))->get();
but if I using
$startDate = "01-12-2015";
$endDate = "31-12-2015";
i get all data...which it's wrong result because 2016 data should not in range...it's somehow like not filtered
since your date datatype is varchar you can try to use str_to_date function in mysql then before using $starDate and $endDate variable convert it's format first.
Sample code is like this.
$startDate = date("Y-m-d", strtotime("01-12-2015"));
$endDate = date("Y-m-d", strtotime("31-12-2015"));
$query = DB::table('test')->whereBetween("str_to_date(date, '%d-%m-%Y')", array($startDate, $endDate))->get();
Hope that helps.
The format shouldn't be a problem; Unless the data you POST are in different format from what the database holds. Make sure that the format for the date field in database matches the format to the ones you store in $startDate, $endDate.
Also I would solve this by taking a slightly different approach. This can become a model function, call it getDataBetweenDates(). Each time you need to query the database, to retrieve the data between a specified range of dates, you do a call to this function from the controller:
Model
public function getDataBetweenDates($startDate, $endDate) {
$range = [$startDate, $endDate];
return $this
->whereBetween('date', $range)
->get();
}
Controller
$startDate = Input::get('start_date');
$endDate = Input::get('end_date');
$model = new Model; // use your model name;
$data = $model->getDataBetweenDates($startDate, $endDate);

Multiple array manipulations and merging

I am an amateur programmer that needs the help of a real one to resolve this beautiful problem, because I must admit that I am really stuck on this one!
In my database I have a « tslines » table that contains a value (sum_week) for a given week(startdate) and a given contract(contract_id)
The fields that are important are : sum_week, user_id , startdate and contract_id
I also have a « users » table, the important values are « first_name, last_name »
I have many workers that have worked on a contract, at different times (startdate, represents the first day of the week)
Example (table below): I can have 3 lines for worker A, and 2 lines for worker B
For some week(startdate), it can happend that no one worked on the contract
I want to show a table with those informations, for contract_id=3(ex) (this field is in tslines table) :
sum_week is a field, I don't want to recalculate with a SQL query
I don’t want to run a query for each weeks to check for each user if he worked on a contract because that would become a problem if I have ex : 30 weeks with 30 users that worked on the project..
I started by building an array of all possible « startdate »
//Selects min and max startdate of the tslines, use $dates->maxdate and ->mindate
$dates = $contract->tslines()->whereIsOfficial(true)->select(DB::raw('MAX(startdate) as maxdate, MIN(startdate) as mindate'))->first();
//Define first date declared in tslines
$loopdate = Carbon::parse($dates->mindate);
$maxdt = Carbon::parse($dates->maxdate);
//While loop to create array of date ranges from min to max
$date_count = 0;
$daterange = array();
while($loopdate->gt($maxdt) == false)
{
$daterange[] = $loopdate->format('Y-m-d');
$loopdate->addDays(7);
$date_count++;
}
I know I have to do some array manipulations but I really don’t know from where to start, even witht the queries..
I can get all the related tslines of contract by doing:
$contract->tslines()->get()
But I dont't know how to build an array that contains user information and all the startdate (even if he didn't work that week)
Can anybody give me some hints.. It would be greatly appreciated!!
Thanks in advance!
Raphaël
Let's start from what we know.
We know which users have worked on which contracts and on what date.
With your function above, we have the max date and the min date a user has started working on a contract.
Solution:
$tslines = $contract->tslines()->orderBy('user_id','ASC')->orderBy('startdate','ASC')->get();
//I didn't see any relationship calls to the user's object, so you'll have to add one of your own. I am assuming, your `tslines` has a relationship `user` here.
$userListResult = $contract->tslines()->with('user')->orderBy('user_id','ASC')->select(\Db::raw('distinct("user_id")')->get();
$dates = $contract->tslines()->whereIsOfficial(true)->select(DB::raw('MAX(startdate) as maxdate, MIN(startdate) as mindate'))->first();
$minDate = Carbon::parse($dates->mindate);
$maxDate = Carbon::parse($dates->maxdate);
//we flatten the array for future use.
$userList = array();
foreach($userListResult as $l)
{
$userList[$l->user_id] = $l->user->first_name.' '.$l->user->last_name;
}
//Assuming you are printing a table in blade
<table>
<?php
//Print the table headers
echo"<tr>
<td>User</td>";
$currDate = clone($minDate);
do
{
echo "<td>".$currDate->format('Y-m-d')."</td>";
$currDate->addDay();
}
while($currDate->diffInDays($maxDate) !== 0);
echo "</tr>";
//Print each user's row
foreach($userlist as $userid => $username)
{
echo "<tr>
<td>
$username
</td>";
$currDate = clone($minDate);
//loop through all the dates in range (min to max date)
do
{
$foundDate = false;
//We check if user has worked on that day
foreach($tslines as $row)
{
if($row->user_id === $userid && $row->startdate->format('Y-m-d') === $currDate->format('Y-m-d'))
{
//Print result if startdate & userid matches
echo "<td>{$row->sum_week}</td>";
$foundDate = true;
//Get out of the loops
break;
}
}
if(!$foundDate)
{
echo "<td>X (didn't work)</td>";
}
$currDate->addDay();
}
while($currDate->diffInDays($maxDate) !== 0);
echo "</tr>";
}
?>
</table>

How do I check whether a value in a query result is null or not? - Active Record - CodeIgniter

I wanted to know how to check whether there is a value present in a table (managers) and then add a 'yes' or 'no' string depending on if there is a value in that table or not.
$this->db->select('employees.first_name, employees.last_name, departments.department_name, departments.department_numb, titles.title');
$this->db->from('employees');
$this->db->where('first_name', $firstname);
$this->db->where('last_name', $lastname);
$this->db->join('department_manager', 'department_manager.emp_numb = employees.emp_numb', 'inner');
$this->db->join('departments', 'departments.department_numb = department_manager.department_numb', 'inner');
$this->db->join('titles', 'titles.emp_numb = employees.emp_numb', 'inner');
$this->db->where('department_name', $dept);
$this->db->where('title', $jobtitle);
$result = $this->db->get();
$data = array();
foreach($result->result() as $row)
{
$entry = array();
$entry['firstname'] = $row->first_name;
$entry['lastname'] = $row->last_name;
$entry['jobtitle'] = $row->title;
$entry['dept'] = $row->department_name;
$entry['deptid'] = $row->department_number;
//$entry['ismanager'] =
$data[] = $entry;
}
return $data;
I want to check whether an employee is present in the table 'department_manager' which is joined by an employees number. So if that employee number is not present in the table 'department_manager' then I want to insert in the array index $entry[ismanager'] a string which says 'no', and if the employee number is present in the table 'department_manager' then I want $entry['ismanager'] to hold the string 'yes'.
But I'm confused as to how to check that the employee is present or not in that table. Do I do it in the active record query or in the foreach loop? And if it is done in the foreach loop then how do I make that comparison as the query is completed?
Why have a field that is basically a calculated value? That's like having fields for quantity per box, quantity of boxes then saving the total items to a third field. Never save to the database something you can gain access to via a quick query. In your query above it's as simple as changing the dept manager join to a left join, including the dept manager id and saying if that field is blank in a record the person is not a manager. Using a LEFT join will return all records whether they have an entry in the management table or not.
Add: department_manager.emp_numb to the select.
The Join:
$this->db->join('department_manager', 'department_manager.emp_numb
= employees.emp_numb', 'left');
Then in the foreach:
if(!$row->department_manager.emp_numb)
{
this person is not a manager;
}
If you feel you really must have that extra field then you can still populate it with the method above.
If you are using MySQL, I think you are looking for:
IFNULL(expr1,expr2)
where:
expr1 == null condition (in your case NULL)
expr2 == replacement value
Source: Control Flow Functions

Resources