Mass update in laravel using foreach - laravel

How to Update mass records without deleting or replacing old one inserted records. Here mine problem is that last inserted record will replace with latest records.
/*DB::table('syllabuses')
->where('course_id', $curse_id)
->Where('semster',$semesterid)
->delete();*/
$Syllabus = Syllabus::find($id);
foreach ($data as $value)
{
//$Syllabus = new Syllabus;//
$Syllabus->slno = $value->SlNo;
$Syllabus->coursecode =$value->cousrecode;
$Syllabus->coursename =$value->coursename;
$Syllabus->credit =$value->credit;
$Syllabus->papertype=$value->papertype;
$Syllabus->deptoffering_name=$value->Deptoffer;
$Syllabus->deptoffering_id=$value->Department;
$Syllabus->dept_id = $details['depart'];
$Syllabus->save();
}

Please try to understand the difference between INSERT and UPDATE first. Definitely update query replace the old values of the relevant record. In your query you are tying updating same "Syllabus".
$Syllabus = Syllabus::find($id);
foreach ($data as $value)
{
//$Syllabus = new Syllabus;//
$Syllabus->slno = $value->SlNo;
$Syllabus->coursecode =$value->cousrecode;
$Syllabus->coursename =$value->coursename;
$Syllabus->credit =$value->credit;
$Syllabus->papertype=$value->papertype;
$Syllabus->deptoffering_name=$value->Deptoffer;
$Syllabus->deptoffering_id=$value->Department;
$Syllabus->dept_id = $details['depart'];
$Syllabus->save();
}
In above code, you find the Syllabus outside of the foreach. Then you update the that found record inside the foreach. If you want to update many "Syllabus", then try this:
foreach ($data as $value)
{
$Syllabus = Syllabus::find("SyllabusID");
$Syllabus->slno = $value->SlNo;
$Syllabus->coursecode =$value->cousrecode;
$Syllabus->coursename =$value->coursename;
$Syllabus->credit =$value->credit;
$Syllabus->papertype=$value->papertype;
$Syllabus->deptoffering_name=$value->Deptoffer;
$Syllabus->deptoffering_id=$value->Department;
$Syllabus->dept_id = $details['depart'];
$Syllabus->save();
}
Or else, if you want to remain old records, please try to create new records in db using following code
foreach ($data as $value)
{
$Syllabus = new Syllabus();
$Syllabus->slno = $value->SlNo;
$Syllabus->coursecode =$value->cousrecode;
$Syllabus->coursename =$value->coursename;
$Syllabus->credit =$value->credit;
$Syllabus->papertype=$value->papertype;
$Syllabus->deptoffering_name=$value->Deptoffer;
$Syllabus->deptoffering_id=$value->Department;
$Syllabus->dept_id = $details['depart'];
$Syllabus->save();
}
Read official laravel documentation for further details: https://laravel.com/docs/5.7/eloquent

Related

Laravel model is updating multiple models instead of single

I am trying to update my model using multiple where conditions.
my code is
public function UpdateEducationData(Request $request)
{
$user = app('user');
// return $request;
$education = eduinfo::where("id", $user->id)->where("exam", $request->type)->first();
// dump sql query for debugging
// $education->rawSql();
// dd($education);
$education->board = $request->board;
// $education->degree = $request->degree;
$education->year = $request->year;
$education->rollno = $request->rollno;
$education->obtainmarks = $request->obtainmarks;
$education->totalmarks = $request->totalmarks;
$education->division = $request->division;
$education->grade = $request->grade;
$education->totalcgpa = $request->totalcgpa;
$education->obtailcgpa = $request->obtailcgpa;
// update education based on exam
$education->save();
return redirect()->back()->with("message", "Education Information Updated Successfully");
return "Update Education Data";
}
My code is updating a eduinfo table based on id and exam. But whenever this function is called it updates all eduinfo records related to that user id.
I tried to update eduinfo table single record but multiple records are being update at once. I dumped eduinfo after retriving the model and yes it's retrieving the single model using first() method but still when save() is called it updates all records of that user id in eduinfo.
I think Your conditions to make a unique record are not.
But if you wanna Just run one time! I have an offer to you.
$flag=true;
if($flag){
$user = \Auth::user();
$education = eduinfo::where('id','=', $user->id)->where('exam','=', $request->type)->first();
$education->board = $request->board;
$education->year = $request->year;
$education->rollno = $request->rollno;
$education->obtainmarks = $request->obtainmarks;
$education->totalmarks = $request->totalmarks;
$education->division = $request->division;
$education->grade = $request->grade;
$education->totalcgpa = $request->totalcgpa;
$education->obtailcgpa = $request->obtailcgpa;
$education->save();
$flag=false;
}
It's depends on my answer.

How do I return records by using chunk()?

I'm using chunk() to find a value from the database based on the question. But how do I return the entityFound[] array?
$chunkRecord = $this->company()->entityValues()->chunk(5,
function ($entityValues) use ($entityFound, $question) {
foreach ($entityValues as $entityValue)
if (str_contains($question, $entityValue->name))
$entityFound[] = $entityValue->name;
return $entityFound;
});
// I want to run this array and do something else.
dd($entityFound);

Save multiple inputs Laravel 5.6

I'm trying to save a data to my database coming from 2 inputs which has multiple values. The scenario is that after a product has been saved, data will be save to my another table with columns 'product_id','price','size'. How ever when I tried to run my code, only the first value is saved in the column 'size', the data in 'price' are fine.
<input name="fix_size[]">
<input name="fix_price[]">
foreach($request->fix_price as $prc){
$cprice = new ContainerPrice;
$cprice->product_id = $id;
$cprice->price = $prc;
foreach($request->fix_size as $size){
$cprice->size = $size;
}
$cprice->save();
}
Remember, fix_size and fix_price are arrays.
You have to get the respective pairs of each fix_size and fix_price. So you have to monitor the index in the loop.
This is one of the possible solution in your problem:
$fix_sizes = $request->fix_size;
foreach($request->fix_price as $i => $prc){
$cprice = new ContainerPrice;
$cprice->product_id = $id;
$cprice->price = $prc;
$cprice->size = $fix_sizes[$i];
$cprice->save();
}
I may suggest to you to master the basic principles of programming and learn to debug codes by yourself.
Try this
foreach($request->fix_price as $prc){
foreach($request->fixed_size as $size){
$cprice = new ContainerPrice;
$cprice->product_id = $id;
$cprice->price = $prc;
$cprice->size = $size;
$cprice->save();
}
}
You could try this:
foreach($request->fix_price as $key => $prc) {
$cprice = new ContainerPrice;
$cprice->product_id = $id;
$cprice->price = $prc;
$cprice->size = $request->input('size')[$key];
$cprice->save();
}
The problem you had is because you loop over all elements inside the main loop and keeping only the last element. In other words, in the foreach loop, you are constantly overriding the $cprice->size property with the last you find.
Now with this code you access the "size" which has the same index as your "price".

Multiple Eloquent Where statements with multiple parameters

I have a parsing problem where I want to get all of the people with a particular subscription but not people who have another type of subscription. The subscriptions are stored in a comma delineated list in the subscriptions table in the subscriptions column. Here is the code I have so far:
$includeQuery = [];
foreach ($includeSegment as $include) {
$singleQuery = ['subscriptions','like', '%'.$include.'%', 'or'];
array_push($includeQuery, $singleQuery);
}
$excludeQuery = [];
foreach ($excludeSegment as $exclude) {
$singleQuery = ['subscriptions', 'not like', '%'.$exclude.'%', 'or'];
array_push($excludeQuery, $singleQuery);
}
$included = Subscription::where($excludeQuery)->where($includeQuery)->get();
I get results back but some of them have the excluded subscriptions in them.
use whereIn and whereNotIn instead :
Subscription::whereIn($includeSegment)->whereNotIn($excludeSegment)->get();
then you dont need to also iterate segments once they are arrays of strings
The problem with code above was in the boolean parameter I had "or" instead of "and". So only if all of the subscriptions for a particular user were present would the record get thrown out. Here is the updated code:
$includeQuery = [];
foreach ($includeSegment as $include) {
$singleQuery = ['subscriptions','like', '%'.$include.'%', 'or'];
array_push($includeQuery, $singleQuery);
}
$excludeQuery = [];
foreach ($excludeSegment as $exclude) {
$singleQuery = ['subscriptions', 'not like', '%'.$exclude.'%', 'and'];
array_push($excludeQuery, $singleQuery);
}
// $included = Subscription::where($excludeQuery)->where($includeQuery)->get();
$included = DB::table('subscriptions')
->join('app_users', 'app_users.customer_number', '=', 'subscriptions.customer_number')
->join('app_datas', 'app_datas.customer_number', '=', 'subscriptions.customer_number')
->where($includeQuery)
->where($excludeQuery)
->select('app_datas.device_token')
->get();

Magento - get bundled products where a simple product belongs to

I want to show all bundles on a simple product's page and so need to retrieve the information. I searched and tried a lot. This post sounds promising, but is either not working or maybe not for my problem:
Magento - get a list of bundled product ids from a product id
I found a solution for grouped products but this can't be applied here.
$grouped_product_model = Mage::getModel('bundle/product_selection');
$groupedParentId = $grouped_product_model->getParentIdsByChild($product->getId());
I found the table catalog_product_bundle_selection to be the right place to search, but I wonder if there is a clean way and existing function to search this table by product_id than just to hack this.
I didn't find a solution in Mage_Bundle.
What did I miss?
After getting first aid from vrnet I wrote a new block class, so I can update the layout
class Thomaier_Catalog_Block_Product_View_BundledSelect extends Mage_Catalog_Block_Product_View
{
protected $_simpleProducts = array( '3' ); // just an example
public function getBundles() {
$bundleIds = array();
$bundlesCollectionModel = Mage::getResourceModel('bundle/selection_collection');
$bundlesCollection = $bundlesCollectionModel->getSelect()
->where('`selection`.`product_id` in (' . join(',', (array)$this->_simpleProducts) . ')');
foreach ($bundlesCollection as $bundleItem) {
$bundleIds[] = $bundleItem->getParentProductId();
}
...
}
}
I skipped some parts. As I mentioned in the comment, the SQL query works fine when I try it in phpmyadmin, but $bundleItem is not created and ->load() throws an exception.
Thanks for advice.
Below is a method I wrote for a client having the same request with an extra : the ability to shuffle the result.
Hope it helps.
protected $_simpleProducts = array(); // Array with IDs of simple products you want bundles from.
protected $_shuffle = false;
public function getBundles() {
$bundleIds = array();
/*Rather than using a collection model
and make operations with getSelect,
a more elegant way is to extend
Mage_Bundle_Model_Mysql4_Selection_Collection
with a method that would be something like
setProductIdsFilter($productIds)*/
$bundlesCollectionModel = Mage::getResourceModel('bundle/selection_collection');
$bundlesCollection = $bundleCollectionModel->getSelect()
->where('`selection`.`product_id` in (' . join(',', (array)$this->_simpleProducts) . ')');
foreach ($bundlesCollection as $bundleItem) {
$bundleIds[] = $bundleItem->getParentProductId();
}
if (count($bundleIds)) {
$allowBundles = Mage::getResourceModel('catalog/product_collection')
->addIdFilter($bundleIds)
->addFieldToFilter('status', Mage_Catalog_Model_Product_Status::STATUS_ENABLED);
if ($this->_shuffle) {
$allowBundles->getSelect()->order('rand()');
}
if ($allowBundles->count()) {
return $allowBundles;
}
}
return;
The following is the best way to work with these. This way you do not rely on a custom query but instead you can use the core methods:
$bundlesCollection = Mage::getResourceModel('bundle/selection')
->getParentIdsByChild($simple_product_ids_array_or_int);
foreach ($bundlesCollection as $bundleProdId) {
//do anything you want with the bundleProdId array elements
}

Resources