How to avoid duplicate entry in database using insert in Laravel? - php

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]
);

Related

How to access array values in laravel

This method i am using for storing currentTime in database using ajax call and its working
public function saveTime(Request $request, $lession_id){
$user = Auth::user();
if($user === null){
return response()->json(['message' => 'User not authenticated', 404]);
}
$video = \App\Lession::where('id',$lession_id)->first();
$lesson_id = $request->lession_id;
$progress = $request->time;
//save them somewhere
$watch_history = $user->watch_history;
$watch_history_array = array();
if ($watch_history == '') {
array_push($watch_history_array, array('lession_id' => $lesson_id, 'progress' => $progress));
} else {
$founder = false;
$watch_history_array = json_decode($watch_history, true);
for ($i = 0; $i < count($watch_history_array); $i++) {
$watch_history_for_each_lesson = $watch_history_array[$i];
if ($watch_history_for_each_lesson['lession_id'] == $lesson_id) {
$watch_history_for_each_lesson['progress'] = $progress;
$watch_history_array[$i]['progress'] = $progress;
$founder = true;
}
}
if (!$founder) {
array_push($watch_history_array, array('lession_id' => $lesson_id, 'progress' => $progress));
}
}
$data['watch_history'] = json_encode($watch_history_array);
$check = User::where('id',$user->id)->update(['watch_history' => $watch_history_array]);
return response()->json(['message' => 'Time saved', 200]);//send http response as json back to the ajax call
}
But when I use this another method to get the time back for playback it's getting the array inside an array
public function getTime(Request $request, $lession_id){
$user = Auth::user();
if($user === null){
return response()->json(['message' => 'User not authenticated', 403]);
}
$user_video = User::where('id',$user->id)->first();
$array = $user_video->watch_history;
foreach ($array as $key => $value) {
echo $check;
}
}
My current Output in a database is as follows
[{"lession_id":"157","progress":"71.449464"},{"lession_id":"156","progress":"92.113123"}]
So help me to get the values out of that for each lession id

Laravel create an array in postman and save in database

I am having troubles at this situation.
This is what I show in Postman
Controller
public function index(Request $request)
{
$user = Auth::guard('api');
if ($user)
{
$parameters=new UserParameters();
$parameters->id_user=Auth::guard('api')->id();
$parameters->day=$request->day;
if($parameters->save())
{
$times=$request->time;
foreach ( $times as $time)
{
$new_time = new TimeParameter();
$new_time->id_parameter = $parameters->id;
$new_time->time = $time[0];
$new_time->hour = $time[1];
$new_time->save();
}
return response()->json(['true' => false, 'message' => 'Saved!']);
}
}
else
{
return response()->json(['error' => false, 'message' => 'User not found!']);
}
}
I stuck at for loop. How can I handle this situation ?
This is what i get in database
This is because of how your key's are named. time[0].time is not valid and maybe it is reading it to time[0] only. Which is why you are only getting the hours. time[0].time = 'morning';
time[0].hour = '10:00';
- then it will not count the .time or the .hour because that is not valid. then it would only make it time[0] which then explains why you are only getting the hours.
With the changes on the postman data that I asked you to do. You can try this solution.
public function index(Request $request)
{
$user = Auth::guard('api');
if ($user)
{
$parameters=new UserParameters();
$parameters->id_user=Auth::guard('api')->id();
$parameters->day=$request->day;
if($parameters->save())
{
$data= $request->all();
foreach ( $data['times'] as $time)
{
$new_time = new TimeParameter();
$new_time->id_parameter = $parameters->id;
$new_time->time = $time[0];
$new_time->hour = $time[1];
$new_time->save();
}
return response()->json(['true' => false, 'message' => 'Saved!']);
}
}
else
{
return response()->json(['error' => false, 'message' => 'User not found!']);
}
}
Problem
I don't know how your code works, because this for ( $times as $time) is not how for works.
Here is a explanation on for
https://secure.php.net/manual/pt_BR/control-structures.for.php
Solution
The as on the for make me think your trying to use the foreach.
And here is how it works:
foreach( $times as $time) the $time is already a single record from the array
So when you do a foreach this is how it should look:
foreach ( $times as $time){
$new_time = new TimeParameter();
$new_time->id_parameter = $parameters->id;
$new_time->time = $time->time;
$new_time->hour = $time->hour;
$new_time->save();
}

I want to replicate one row into 365 row in one table in Laravel

I want to save the same data with 365 records within one table. I'm new to Laravel.
I've tried with replicate() but was unsuccessful. I tried this on the Apache server and used Laravel5.7.
my controller
public function price_save(Request $request) {
$price=new Price();
$price->price=$request->price;
$price->extra_bed=$request->extra_bed;
$price->room_id=$request->room;
$id=$request->room;
$price = Price::find($id);
if(null !== $price){
$new = $price->replicate();
if(null !== $new){
$new->push();
// $price->save();
}
I am NOT sure about your code, But you can customize it as per your needs, To just get idea :
$model = User::find($id);
$model->load('invoices');
$newModel = $model->replicate();
$newModel->push();
foreach($model->getRelations() as $relation => $items){
foreach($items as $item){
unset($item->id);
$newModel->{$relation}()->create($item->toArray());
}
}
Credits
public function price_save(Request $request, int $id)
{
if ($id > 365) {
return;
}
$price = new Price();
$price->price = $request->price;
$price->extra_bed = $request->extra_bed;
$price->room_id = $request->room;
$price->save();
$existing = Price::find($request->room);
if ($existing) {
$request = $request->replace([
'price' => $price->price,
'extra_bed' => $price->extra_bed,
'room_id' => $price->room,
]);
}
return price_save($request, $id++);
}

Codeigniter transaction for all queries within a function

I have these following functions.
public function importExcelFile(){
$file = $_FILES['file']['tmp_name'];
$data = extract_excel_data($file);
$i = 0;
foreach($data['values'] as $dataValues) {
$categories = [];
$brands = [];
$models = [];
foreach($dataValues as $value){
if(array_filter($value)) {
/* If a row does not contain brand/category/model for the product then fetch the resp. info. from previous row */
if(empty(trim($value[0]))) {
$categories[] = $prev_cat;
} else {
$categories[] = strtoupper(trim($value[0]));
$prev_cat = strtoupper(trim($value[0]));
}
if(empty(trim($value[1]))) {
$brands[] = $prev_brand;
} else {
$brands[] = strtoupper(trim($value[1]));
$prev_brand = strtoupper(trim($value[1]));
}
if(empty(trim($value[2]))) {
$models[] = $prev_model;
} else {
$models[] = $value[2];
$prev_model = $value[2];
}
}
}
//insert device category
$this->insert_setups('category', $categories);
//insert brand
$this->insert_setups('brand', $brands);
// Check if branch already exists in the database
$check_branch = $this->global_model->getDetailByWhere('branch', array('name'=>$data['branch'][$i].' branch'))->result();
$branch_arr = [];
//insert branch
if(empty($check_branch)) {
$branch_arr = array(
'name' => $data['branch'][$i].' branch',
'location' => $data['branch'][$i],
'status' => 1,
'created_by' => $this->session->userdata('id'),
'created_on' => date('Y-m-d')
);
$this->global_model->insertData('branch', $branch_arr);
}
$branch_id = $this->global_model->getDetailByWhere('branch', array('name'=>$data['branch'][$i].' branch'))->row()->id;
$db_device_categories = [];
$db_brands = [];
// get categoris, brands
$db_device_categories = $this->arrangeArray('category', $where =array());
$db_brands = $this->arrangeArray('brand', $where =array());
//detail_print($db_brands);
// insert new models from database
foreach(array_unique($models) as $model_key=>$model){
$check_model = $this->global_model->getDetailByWhere('model', array('name'=>$model))->result();
$insert = [];
if(empty($check_model)){
$insert = array(
'name' => $model,
'item_type' => 1,
'category_id' => $db_device_categories[$categories[$model_key]],
'brand_id' => $db_brands[$brands[$model_key]],
'created_by' => $this->session->userdata("id"),
'created_on' => date('Y-m-d'),
);
$this->global_model->insertData('model', $insert);
}
}
$db_device_models = [];
// get models from database
$db_device_models = $this->arrangeArray('model', $where = array('item_type'=>1));
$categoriy_id = [];
$brand_id = [];
$model_id = [];
$opening_stock = [];
// arrange the exported array with respective id
foreach($dataValues as $values){
if(array_filter($values)) {
if(empty(trim($values[0]))) {
$category_id = $prev_cat;
} else {
$category_id = strtoupper(trim($values[0]));
$prev_cat = strtoupper(trim($values[0]));
}
if(empty(trim($values[1]))) {
$brand_id = $prev_brand;
} else {
$brand_id = strtoupper(trim($values[1]));
$prev_brand = strtoupper(trim($values[1]));
}
if(empty(trim($values[2]))) {
$model_id = $prev_model;
} else {
$model_id = $values[2];
$prev_model = $values[2];
}
$opening_stock[] = array(
'category_id' => $db_device_categories[$category_id],
'brand_id' => $db_brands[$brand_id],
'model_id' => $db_device_models[$model_id],
'imei' => (string)$values[3],
'cost_price' => isset($values[5]) ? $values[5] : 0,
'selling_price' => isset($values[6]) ? $values[6] : 0
);
}
}
$group_by_model = [];
// group the array by model_id
foreach(array_unique($models) as $model1){
$where = $db_device_models[$model1];
$group_by_model[] = array_filter($opening_stock, function($elements) use ($where){
return $elements["model_id"] == $where;
});
}
if(!$this->purchase_model->insertOpeningStock($group_by_model, $branch_id)){
$this->session->set_flashdata('error', 'Opening stock of devices insertion failed.');
redirect('purchase/uploadExcelFile');
}
$i++;
}
$this->session->set_flashdata('success', 'Opening stock of devices added successfully.');
redirect('purchase/uploadExcelFile');
}
private function arrangeArray($table, $where){
$list = $this->global_model->getDetailByWhere($table, $where)->result_array();
foreach($list as $item){
$name = $item['name'];
$arranged_list[$name] = $item['id'];
}
return !empty($arranged_list) ? $arranged_list : NULL;
}
private function insert_setups($table_name, $setups){
foreach(array_unique($setups) as $value){
$check_setup = $this->global_model->getDetailByWhere($table_name, array('name'=>$value))->result();
if(empty($check_setup)){
$insert = array(
'name' => $value,
'created_by' => $this->session->userdata("id"),
'created_on' => date('Y-m-d'),
);
$this->global_model->insertData($table_name, $insert);
}
}
}
What this function does is, it extracts data from the uploaded excel file and inserts the data to various tables accordingly. Now as you can see, there are multiple queries running in different locations inside the importExcelFile() method. So my question is, how do I use codeigniter transaction in such a way that all the queries inside this function are performed atomically. If any one query fails, all other query's work is rolled back. Also, is this code considered clean ?
P.S. I'm so sorry if my last question was inappropriate here.
this might be helpful to you.
transactions in codeigniter
$this->db->trans_begin();
$this->db->query('AN SQL QUERY...');
$this->db->query('ANOTHER QUERY...');
$this->db->query('AND YET ANOTHER QUERY...');
if ($this->db->trans_status() === FALSE)
{
$this->db->trans_rollback();
}
else
{
$this->db->trans_commit();
}

How to edit Magento's API function "items()" to get the ImageUrl of the product

I am trying to get the Image URL of the products by editing the Magento's API items() function. I have used $product-> getImageUrl() to get the URL but I am getting wrong URL.
The URL that I am getting is of the default Image which we place for the products which do not have image(Image Comming Soon like Image's url).
I am calling the function from Android Client using XML-RPC.
I am getting other details of the product correct,but the URL that I am getting for the products is wrong. And, all the URLs of the different products I am getting are same.
FYI, The URL that I am getting in the response is like :
http://192.168.1.237/machinetest/media/catalog/product/cache/0/image/265x/9df78eab33525d08d6e5fb8d27136e95/images/catalog/product/placeholder/image.jpg
The function that I am editing is as followed :
public function items($filters = null, $store = null)
{
$collection = Mage::getModel('catalog/product')->getCollection()
->addStoreFilter($this->_getStoreId($store))
->addAttributeToSelect('name');
if (is_array($filters)) {
try {
foreach ($filters as $field => $value) {
if (isset($this->_filtersMap[$field])) {
$field = $this->_filtersMap[$field];
}
$collection->addFieldToFilter($field, $value);
}
} catch (Mage_Core_Exception $e) {
$this->_fault('filters_invalid', $e->getMessage());
}
}
$result = array();
foreach ($collection as $product) {
//$result[] = $product->getData();
$result[] = array( // Basic product data
'product_id' => $product->getId(),
'sku' => $product->getSku(),
'name' => $product->getName(),
'set' => $product->getAttributeSetId(),
'type' => $product->getTypeId(),
'category_ids'=> $product->getCategoryIds(),
'url_path' => $product-> getImageUrl() // Added the Method here
);
}
return $result;
}
Just write that please try this way..you will get the Solution on the Top
You can able to get Images using this code just go through it and you will get images
public function items($filters = null, $store = null)
{
$collection = Mage::getModel('catalog/product')->getCollection()
->addStoreFilter($this->_getStoreId($store))
->addAttributeToSelect('name');
if (is_array($filters)) {
try {
foreach ($filters as $field => $value) {
if (isset($this->_filtersMap[$field])) {
$field = $this->_filtersMap[$field];
}
$collection->addFieldToFilter($field, $value);
}
} catch (Mage_Core_Exception $e) {
$this->_fault('filters_invalid', $e->getMessage());
}
}
$result = array();
foreach ($collection as $product) {
// $result[] = $product->getData();
$_product = Mage::getModel('catalog/product')->load($product->getId());
$_image=$_product->getImageUrl();
$result[] = array( // Basic product data
'product_id' => $product->getId(),
'sku' => $product->getSku(),
'name' => $product->getName(),
'set' => $product->getAttributeSetId(),
'type' => $product->getTypeId(),
'category_ids'=> $product->getCategoryIds(),
'image_url_path' => $_image
);
}
return $result;
}
hope it's work
if you have any queries tell me i will help you!
I was working with images recently and I believe I have pretty good understanding about it.
I don't think what Josua said is the "real" correct answer. It is good that his answer can solve your problem but I just couldn't stand seeing misleading information.
As for his first option, it is "correct".
Let me break down the code:
Mage_Catalog_Model_Product_Media_Config
public function getMediaUrl($file)
{
$file = $this->_prepareFileForUrl($file);
if(substr($file, 0, 1) == '/') {
return $this->getBaseMediaUrl() . $file;
}
return $this->getBaseMediaUrl() . '/' . $file;
}
public function getBaseMediaUrl()
{
return Mage::getBaseUrl('media') . 'catalog/product';
}
protected function _prepareFileForUrl($file)
{
return str_replace(DS, '/', $file);
}
As you can see, it just simply add media/ + catalog/product + $file.
$file is taken from database, the value will be something like /e/x/example.jpeg
Your uploaded product images are stored inside those folders.
Now, for the problem why $product-> getImageUrl() give you wrong URL is still unknown.
The code that Josua suggest for second option:
$this->helper('catalog/image')
->init($product, $type)
->resize(163, 100);
is "almost" the same with $product->getImageUrl(), it just have difference in resize
Mage_Catalog_Model_Product
public function getImageUrl()
{
return (string)$this->_getImageHelper()->init($this, 'image')->resize(265);
}
So for his second option, it will give the same result with your old code.
I don't know why did he suggest the second option, I think he never check what is behind those functions (not a good idea as it can lead to wrong information)
When you call for $product->getImageUrl(), it will try to load your image from cache if it exists, if not, it will load the image from database (for the path and then will look for your correct image from media folder) and create the cache. If it is unable to find the image or an error occurred, it will get the placeholder image.
My suggestion is to check if there is an exception thrown. You need to use your old code $product->getImageUrl(). Open your app/code/core/Mage/Catalog/Helper/Image.php
Then go to:
Mage_Catalog_Helper_Image
public function __toString()
{
try {
if( $this->getImageFile() ) {
$this->_getModel()->setBaseFile( $this->getImageFile() );
} else {
$this->_getModel()->setBaseFile( $this->getProduct()->getData($this->_getModel()->getDestinationSubdir()) );
}
if( $this->_getModel()->isCached() ) {
return $this->_getModel()->getUrl();
} else {
if( $this->_scheduleRotate ) {
$this->_getModel()->rotate( $this->getAngle() );
}
if ($this->_scheduleResize) {
$this->_getModel()->resize();
}
if( $this->getWatermark() ) {
$this->_getModel()->setWatermark($this->getWatermark());
}
$url = $this->_getModel()->saveFile()->getUrl();
}
} catch( Exception $e ) {
//put log to show error message
Mage::log($e->getMessage());
$url = Mage::getDesign()->getSkinUrl($this->getPlaceholder());
}
return $url;
}
Put Mage::log($e->getMessage()); to log if there is an exception thrown. Most likely your placeholder image is called because there was an exception thrown.
It is just a suggestion from me to ensure there is nothing's wrong with your image / other things as in fact you have solved your problem by directly get the image from media/catalog/product/...
Another correction for Josua's code:
Notice the $full_product = Mage::getModel('catalog/product')->load($product_id);
It is absolutely unnecessary since inside foreach($collection as $product), the product object will be loaded, so another load of product is unnecessary (also $product_id is undefined)
UPDATE, just fixing your code:
public function items($filters = null, $store = null)
{
$collection = Mage::getModel('catalog/product')->getCollection()
->addStoreFilter($this->_getStoreId($store))
->addAttributeToSelect(array('name','image'));
//->addAttributeToSelect('name'); add another select, either image / small_image / thumbnail, modify it as you need
if (is_array($filters)) {
try {
foreach ($filters as $field => $value) {
if (isset($this->_filtersMap[$field])) {
$field = $this->_filtersMap[$field];
}
$collection->addFieldToFilter($field, $value);
}
} catch (Mage_Core_Exception $e) {
$this->_fault('filters_invalid', $e->getMessage());
}
}
$result = array();
foreach ($collection as $product) {
//$result[] = $product->getData();
$result[] = array( // Basic product data
'product_id' => $product->getId(),
'sku' => $product->getSku(),
'name' => $product->getName(),
'set' => $product->getAttributeSetId(),
'type' => $product->getTypeId(),
'category_ids'=> $product->getCategoryIds(),
'url_path' => $product-> getImageUrl() // Added the Method here
);
}
return $result;
}
Your code was awesome!
Yes, you can get image url with :
'url_path' => Mage::getModel('catalog/product_media_config')
->getMediaUrl($product->getImage());//getSmallImage(), getThumbnail()
or another option by calling :
$type = 'small_image';
'url_path' => $this->helper('catalog/image')
->init($product, $type)
->resize(163, 100);
can be changed by 'image' small_image' or 'thumbnail'
Default:
Base Image: 265x265 pixel
Small Image: 135x135 pixel
Thumbnail Image: 75x75 pixel
The easier option (detailed):
public function items($filters = null, $store = null)
{
$collection = Mage::getModel('catalog/product')->getCollection()
->addStoreFilter($this->_getStoreId($store))
->addAttributeToSelect('name');
if (is_array($filters)) {
try {
foreach ($filters as $field => $value) {
if (isset($this->_filtersMap[$field])) {
$field = $this->_filtersMap[$field];
}
$collection->addFieldToFilter($field, $value);
}
} catch (Mage_Core_Exception $e) {
$this->_fault('filters_invalid', $e->getMessage());
}
}
$result = array();
foreach ($collection as $product) {
//$result[] = $product->getData();
$full_product = Mage::getModel('catalog/product')->load($product_id);
$result[] = array( // Basic product data
'product_id' => $product->getId(),
'sku' => $product->getSku(),
'name' => $product->getName(),
'set' => $product->getAttributeSetId(),
'type' => $product->getTypeId(),
'category_ids'=> $product->getCategoryIds(),
'url_path' => $full_product->getImageUrl(),
// 'product_path' => $full_product->getProductUrl()
// you can call $full_product->getData();
);
}
return $result;
}

Categories