hi i have developed my project in Laravel 4.2 version and i have an array of record and i want to insert this data into database using built-in insert() function but i want to update those entries which are already inserted otherwise insert the record. Can anyone help me here is my sample code
public static function followAllUsers($user_data) {
$responce = array();
$data = array();
foreach ($user_data['following_id'] as $key => $value) {
$following = UserBussinessLogic::checkAndValidateUser($value);
if ($following != true) {
$responce = Utility::Responce('invalid_user', FALSE, $value);
break;
} else {
if (FriendBussinessLogic::isAlreadyFollowed($user_data['id'], $value)) {
continue;
}
$data[] = array('follower_id' => $user_data['id'], 'following_id' => $value, 'created_at' => date('Y-m-d H:i:s'));
$followData['notifyAbleUsers'][] = $value;
}
}
if ($following) {
if (!empty($data)) {
if (Friend::insert($data)) {
$followData['created_at'] = date('Y-m-d H:i:s');
$followData['follower_id'] = $user_data['id'];
$responce = Utility::Responce('friend_followed', TRUE, $followData);
} else {
$responce = Utility::Responce('general_error', FALSE);
}
} else {
$responce = Utility::Responce('already_followed', TRUE);
}
}
return $responce;
}
Thank you
A little lesser known function that is also available in Laravel 4.2 is: updateOrCreate
Here's an example on how to use it:
// If there's a flight from Oakland to San Diego, set the price to $99.
// If no matching model exists, create one.
$flight = App\Flight::updateOrCreate(
['departure' => 'Oakland', 'destination' => 'San Diego'],
['price' => 99]
);