Laravel Eloquent ORM save: update vs create - laravel

I've got a table and I'm trying to use the save() method to update/create lines. The problem is that it always create new lines. The following code gives me about 12 lines each time I run it. They don't have a unique id before inserting them but the combination of name and DateTimeCode is unique. Is there's a way to use those two in order for laravel to recognize them as exist()? Should I consider using if exist with create and update instead?
foreach ($x as $y) {
$model = new Model;
$model->name = ''.$name[$x];
$model->DateTimeCode = ''.$DateTimeCode[$x];
$model->value = ''.$value[$x];
$model->someothervalue = ''.$someothervalue[$x];
$model->save();
};

I assume this would work in laravel 4.x:
foreach ($x as $y) {
$model = Model::firstOrCreate(array('name' => name[$x], 'DateTimeCode' => DateTimeCode[$x]));
$model->value = ''.$value[$x];
$model->someothervalue = ''.$someothervalue[$x];
$model->save();
};

I think that in this case you will need to search for it before updating or creating:
foreach ($x as $y) {
$model = Model::where('name', name[$x])->where('DateTimeCode', DateTimeCode[$x])->first();
if( ! $model)
{
$model = new Model;
$model->name = ''.name[$x];
$model->DateTimeCode = ''.DateTimeCode[$x];
}
$model->value = ''.$value[$x];
$model->someothervalue = ''.$someothervalue[$x];
$model->save();
};

Related

Foreach loop is showing error while storing multiple id's

I am creating a group and also storing users id's in it but its showing error in foreach loop i.e. Invalid argument supplied for foreach().
Here is my controller code :
public function createGroup(Request $request)
{
$user_id = request('user_id');
$member = request('member');
$data = array(
'name'=>$request->name,
);
$group = Group::create($data);
if($group->id)
{
$resultarr = array();
foreach($member as $data){
$resultarr[] = $data['id'];
}
$addmem = new GroupUser();
$addmem->implode(',', $resultarr);
$addmem->group_id = $group->id;
$addmem->status = 0;
$addmem->save();
return $this->sendSuccessResponse([
'message'=>ResponseMessage::statusResponses(ResponseMessage::_STATUS_GROUP_SUCCESS)
]);
}
}
I am adding values like this,
Desired Output,
I just want that each member to store with different id's in table and group id will be same.
Please help me out
Avoid that if check, it does absolute nothing.
if($group->id)
Secondly your input is clearly a string, explode it and you will have the expected results. Secondly don't save it to a temporary variable, create a new GroupUser immediately.
foreach(explode(',', $member) as $data){
$addmem = new GroupUser();
$addmem->user_id = $data;
$addmem->group_id = $group->id;
$addmem->status = 0;
$addmem->save();
}
That implode line makes no sense at all, i assumed there is a user_id on the GroupUser relation.
u need to send array from postman
like
Key | value
member[] | 6
member[] | 3
or
$memberArray = explode(",", $member = request('member'))
if($group->id)
{
$resultarr = array();
foreach($memberArray as $data){
$resultarr[] = $data['id'];
}
$addmem = new GroupUser();
$addmem->implode(',', $resultarr);
$addmem->group_id = $group->id;
$addmem->status = 0;
$addmem->save();
return $this->sendSuccessResponse([
'message'=>ResponseMessage::statusResponses(ResponseMessage::_STATUS_GROUP_SUCCESS)
]);
}

Laravel : How can i get old and new value by updateOrCreate

I want update or create in data base
but i want get the old value and updated value because i want to compare between these two value
for example
this item in table user
name = Alex and Order = 10
so now i want update this person by
name = Alex and Order = 8
Now After updating or creating if not exist
just for update i want get
Old order 10 | And new Order 8
I want compare between these order
i have tryin getChange() and getOriginal() but two the function give me just the new value.
Please Help
You can get the old value using getOriginal if you have the object already loaded.
For example :
$user = User::find(1);
$user->first_name = 'newname';
// Dumps `oldname`
dd($user->getOriginal('first_name'));
$user->save();
However in case of updateOrCreate, you just have the data. I am not sure about a way to do it using updateOrCreate but you can do simply do :
$user = User::where('name', 'Alex')->first();
$newOrder = 10;
if($user){
$oldOrder = $user->getOriginal('order');
$user->order = $newOrder;
$user->save();
}
Is the name unique in the table? Because if it is not you will have updates on multiple rows with the same data.
So the best approach is to use the unique column which is probably the ID.
User::updateOrCreate(
[ 'id' => $request->get('id') ], // if the $id is null, it will create new row
[ 'name' => $request->get('name'), 'order' => $request->get('order') ]
);
Solution
$model = Trend::where('name', $trend->name)->first();
if ($model) {
$model->old_order = $model->getOriginal('order');
$model->order = $key + 1;
$model->save();
} else {
Trend::where('order', $key + 1)->delete();
$new = new Trend();
$new->name = $trend->name;
$new->old_order = $key + 1;
$new->order = $key + 1;
$new->tweet_volume = $trend->tweet_volume;
$new->save();
}

Using JFactory::getDbo()->insertObject with on duplicate key update

How to use:
JFactory::getDbo()->insertObject('#__card_bonus', $object);
with on duplicate key update ?
You have a few options:
1) Check for an entity id. This is my preferred option, because it only uses a single query, is reusable for any object, and is database agnostic - meaning it will work on whichever DBMS you choose, whereas the other two options are exclusive to MySQL.
if (isset($object->id)) {
$db->updateObject('#__card_bonus', $object);
}
else {
$db->insertObject('#__card_bonus', $object, 'id');
}
I often create an abstract model with a save(stdClass $object) method that does this check so I don't have to duplicate it.
2) Write your own query using the MySQL ON DUPLICATE KEY UPDATE syntax, which is a proprietary extension to the SQL standard, that you have demonstrated understanding of.
3) Write your own query using MySQL's proprietary REPLACE INTO extension.
<?php
$jarticle = new stdClass();
$jarticle->id = 1544;
$jarticle->title = 'New article';
$jarticle->alias = JFilterOutput::stringURLSafe($jarticle->title);
$jarticle->introtext = '<p>re</p>';
$jarticle->state = 1;
$jarticle->catid = 13;
$jarticle->created_by = 111;
$jarticle->access = 1;
$jarticle->language = '*';
$db = JFactory::getDbo();
try {
$query = $db->getQuery(true);
$result = JFactory::getDbo()->insertObject('#__content', $jarticle);
}
catch (Exception $e){
$result = JFactory::getDbo()->updateObject('#__content', $jarticle, 'id');
}
I use this method - are not fully satisfied, but ...
or for not object method:
$query = $db->getQuery(true);
$columns = array('username', 'password');
$values = array($db->quote($username), $db->quote($password));
$query
->insert($db->quoteName('#__db_name'))
->columns($db->quoteName($columns))
->values(implode(',', $values));
$query .= ' ON DUPLICATE KEY UPDATE ' . $db->quoteName('password') . ' = ' . $db->quote($password);
$db->setQuery($query);
JFactory::getDbo()->insertObject('#__card_bonus', $object, $keyName);
The name of the primary key. If provided the object property is updated.
Joomla doc ...

How to insert values in another table in controller joomla

I am using joomla 3.1.1 and joomshopping. i need to insert values in another table at same time when user register on website. In user controller i need to insert values in my custom table. can i use a direct insert query in my controller file. this is function in controller file to register user. Where i can put my code to insert data in another table.
function registersave(){
JSession::checkToken() or jexit(JText::_('JINVALID_TOKEN'));
$mainframe = JFactory::getApplication();
$jshopConfig = JSFactory::getConfig();
$config = JFactory::getConfig();
$db = JFactory::getDBO();
$params = JComponentHelper::getParams('com_users');
$lang = JFactory::getLanguage();
$lang->load('com_users');
$post = JRequest::get('post');
JPluginHelper::importPlugin('captcha');
$dispatcher = JDispatcher::getInstance();
$res = $dispatcher->trigger('onCheckAnswer',$post['recaptcha_response_field']);
if(!$res[0]){
JError::raiseWarning('','Invalid Captcha');
$this->setRedirect("index.php?option=com_jshopping&controller=user&task=register",'','',$jshopConfig->use_ssl);
}
else
{
JPluginHelper::importPlugin('jshoppingcheckout');
$dispatcher = JDispatcher::getInstance();
if ($params->get('allowUserRegistration')==0){
JError::raiseError( 403, JText::_('Access Forbidden'));
return;
}
$usergroup = JTable::getInstance('usergroup', 'jshop');
$default_usergroup = $usergroup->getDefaultUsergroup();
if (!$_POST["id"]){
}
$post['username'] = $post['u_name'];
$post['password2'] = $post['password_2'];
//$post['name'] = $post['f_name'].' '.$post['l_name'];
$post['mailing_list'] = $post['mailing_list'];
$hear = '';
$post['where_did_you_purchase'] = $post['where_did_you_purchase'];
$post['ages_of_your_children'] = $agesofchilderen;
$post['comments_or_suggestions'] = $post['comments_or_suggestions'];
$post['vehicle_2'] = $post['vehicle_2_model'].'-'.$post['vehicle_2_year'];
if ($post['birthday']) $post['birthday'] = getJsDateDB($post['birthday'], $jshopConfig->field_birthday_format);
$dispatcher->trigger('onBeforeRegister', array(&$post, &$default_usergroup));
$row = JTable::getInstance('userShop', 'jshop');
$row->bind($post);
$row->usergroup_id = $default_usergroup;
$row->password = $post['password'];
$row->password2 = $post['password2'];
if (!$row->check("register")){
JError::raiseWarning('', $row->getError());
$this->setRedirect(SEFLink("index.php?option=com_jshopping&controller=user&task=register",1,1, $jshopConfig->use_ssl));
return 0;
}
$user = new JUser;
$data = array();
$data['groups'][] = $params->get('new_usertype', 2);
$data['email'] = JRequest::getVar("email");
$data['password'] = JRequest::getVar("password");
$data['password2'] = JRequest::getVar("password_2");
//$data['name'] = $post['f_name'].' '.$post['l_name'];
$data['username'] = JRequest::getVar("u_name");
$useractivation = $params->get('useractivation');
$sendpassword = $params->get('sendpassword', 1);
if (($useractivation == 1) || ($useractivation == 2)) {
jimport('joomla.user.helper');
$data['activation'] = JApplication::getHash(JUserHelper::genRandomPassword());
$data['block'] = 1;
}
//echo $row->getTableName();
//print_r($row);
//die("kkk");
$user->bind($data);
$user->save();
$row->user_id = $user->id;
unset($row->password);
unset($row->password2);
if (!$db->insertObject($row->getTableName(), $row, $row->getKeyName())){
JError::raiseWarning('', "Error insert in table ".$row->getTableName());
$this->setRedirect(SEFLink("index.php?option=com_jshopping&controller=user&task=register",1,1,$jshopConfig->use_ssl));
return 0;
}
}
}
Try this,
Please do not edit Joomla core files.
If you need to add register data on your custom table the create a User Plugin.
Joomla provides lot of plugin events in your case you can use onUserAfterSave. event
Create a User plugin with onUserAfterSave event then simply use the Joomla DB library to your custom table entries.
Hope it helps..

CakePHP serializing objects

I'm stuck with the following problem:
I have a class CartItem. I want to store array of objects of CartItem in session (actually i'm implementing a shopping cart).
class CartItem extends AppModel{
var $name = "CartItem";
var $useTable = false;
}
I tried this:
function addToCart(){
$this->loadModel("Cart");
$this->layout = false;
$this->render(false);
$cart = array();
$tempcart = unserialize($this->Session->read("cart"));
if(isset($tempcart)){
$cart = $tempcart;
}
$productId = $this->request->data("id");
if(!$this->existsInCart($cart, $productId)){
$cartItem = new Cart();
$cartItem->productId = $productId;
$cartItem->createdAt = date();
$cart[] = $cartItem;
$this->Session->write("cart", serialize($cart));
echo "added";
}
else
echo "duplicate";
}
I think I'm writing these lines wrong:
$tempcart = unserialize($this->Session->read("cart"));
$this->Session->write("cart", serialize($cart));
as I'm not getting data from the session.
You are trying to add the whole Cart object to the session.
You should just add an array, like
$cart[] = array(
'productId' => $productId,
'createdAt' => date('Y-m-d H:i:s')
);
If you need to add an object to a session, you can use __sleep and __wakeup magic functions but I think in this case it's better to just add only the product id and date to the session.

Resources