here's a rough sample of my actual code:
$start_date = '01/02/2003';
for($i=1 ; $i<3 ; $i++){
$expiration_date = $start_date->addMonth(12);
}
dump($expiration_date ); //outputs 01/02/2005
dd($start_date); //outputs 01/02/2005
My Question is that why is my start_date variable also becomes the same with the expiration_date variable.
I need the start date at the end of the loop to still have its original value which is 01/02/2003.
When you run addMonth methods against a Carbon object it updates the object itself.
Here's what you need to do:
$expiration_date = $start_date->copy()->addMonth(12);
The copy creates a new Carbon object
Check out the documentation
Related
Hello i want to update a single value on another table using laravel. This is the code i have done until now but doesnt seem to work:
$amount = Product::findorFail($request->products[$i]);
$total_value = $request->amount[$i] + $amount->amount;
$amount->update(['amount', $total_value]);
dd($total_value);
with dd i see that the result is correct but the update function is not, the query im trying to make is
update table set amount=x where id=y
You have multiple choices. The shortes are:
$amount->update(['amount'=> $amount->amount + request->amount[$i]]);
or
Product::findorFail($request->products[$i])->increment('amount', $request->amount[$i]);
you could change your code like below
$amount = Product::findorFail($request->products[$i]);
$total_value = $request->amount[$i] + $amount->amount;
$amount->amount=$total_value;
$amount->update();
or as mentioned in comments you could use eloquent increment function
I try to create a new table based on the existing table. If the table value in A = 'TC' or '0', the table value in B will be '0', else the table value in B will follow the table value in A.
This is what I have tried, but I'm not sure about the logic that I code. Hopefully, someone will help me.
$subject = Scsj::get();
if ($subject->teknologi_dan_sistem_maklumat=='TC'||'0') {
$subject->teknologi_dan_sistem_maklumat=='0';
} else {
$subject->teknologi_dan_sistem_maklumat=='1';
}
First of all, you use the equal operator to set the variable. As 1000Nettles said, get() will return you a collection of data. If you wish to retreive an object, use the first() method.
Besides, I would rewrite your code to make it smaller:
$subject = Scsj::first();
$var = $subject->teknologi_dan_sistem_maklumat;
if ($var =='TC'|| $var == '0') {
$subject->teknologi_dan_sistem_maklumat = '0';
} else {
$subject->teknologi_dan_sistem_maklumat = '1';
}
Edit:
You are trying to make a new database record, setting the value of the old database record wont help unless you plan on updating the record.
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
I am using laravel 4. But I am facing problem with finding the difference between two date: one coming from database table and another one is current datetime. From the date difference I am expecting 1 hour or 1 day. I've tried few solution but can't fix this yet. And also I don't know the better way to solve it. If you guys have any solution, please provide me an example. Please tell me if I need any library. Here is my code:
$lecture_id = Input::get('lecture_id');
$delegate_id = Input::get('delegate_id');
// $newDate = new Datetime();
$lecture = Lecture::find($lecture_id);
// $lec_date = Date::forge($lecture->start_time);
// $lec_date = new Datetime($lecture->start_time);
$lec_date = $lecture->start_time->diffForHumans(Carbon::now());
if ( $lec_date > 1) {
LectureDelegate::create(array(
'lecture_id' => Input::get('lecture_id'),
'delegate_id'=> Input::get('delegate_id')
));
return Redirect::to('/')->with('message', 'Your are successfully apply to the lecture');
}
Should be:
$lec_date = Carbon::createFromTimeStamp( strtotime( $lecture->start_time ) )->diffForHumans();
or possibly:
$lec_date = $lecture->start_time->diffForHumans();
If you add this to your Lecture.php model:
public function getDates()
{
return array('created_at', 'updated_at', 'deleted_at', 'start_time');
}
From the documentation:
By default, Eloquent will convert the created_at, updated_at, and
deleted_at columns to instances of Carbon...
You may customize which fields are automatically mutated, and even
completely disable this mutation, by overriding the getDates method of
the model.
As for diffForHumans the documentation states:
The lone argument for the function is the other Carbon instance
to diff against, and of course it defaults to now() if not specified.
update
If the timestamp from the database being passed to diffForHumans is in the future, Carbon automatically makes the return like:
When comparing a value in the future to default now:
1 hour from now
5 months from now
When comparing a value in the past to another value:
1 hour before
5 months before
I need to save current date and I supposed I must modify this code into application\libraries\grocery_crud.php
line # 253
case 'date':
/*if(!empty($value) && $value != '0000-00-00' && $value != '1970-01-01')
{
list($year,$month,$day) = explode("-",$value);
$value = date($this->php_date_format, mktime (0, 0, 0, (int)$month , (int)$day , (int)$year));
}
else
{
$value = '';
}*/
$value = // some code with current date
It's in that way? or maybe there is another solution, hope can help me, thanks in advance!
Sometimes you may not be able to change the column type from datetime to timestamp.
On these scenarios, considering a GroceryCrud application, there are two possible (and very easy) solutions:
1) Use callback_insert, create your custom insert logic and set the value for the datetime column using a function like NOW() or GETDATE() depending on the DB your are using: $this->db->set('dateTimeColumnName', 'NOW()', FALSE);
2) You can use the callback_before_insert, and inside it, you can call the function date() from PHP, and set there the current date for your insert in the respective array or object attribute that will be passed / returned for the auto-insert be processed right after the callbackĀ“s execution