Create or update rows Laravel - laravel

I try to update or create a table with data from request, on update it works, but on create I can do just for 1. So, if I have 4 new items, just 1 is saved, not sure why, and no errors. If I dump the request I have all values.
$answers = new LkpAnswer;
foreach ($request->items as $key => $item) {
if (isset($item['id'])) {
$answers->where('id', $item['id'])->update($item);
} else {
$answers->fill($item)->save();
}
}

Please Try the following code:
foreach ($request->items as $key => $item) {
if (isset($item['id'])) {
LkpAnswer::where('id', $item['id'])->update($item);
} else {
$answers = new LkpAnswer; //new up an empty model(object) then fill it with your array of data, and finally save it.
$answers->fill($item)->save();
}
}

This should be achievable neatly with built in methods:
foreach ($request->items as $item) {
LkpAnswer::updateOrCreate($item['id'],$item);
}
Make sure that the relevant fields are fillable - see mass assignment protection.

Related

How to insert array data in laravel 5.4

I have a product table and device table.
I have joined these two tables where I have selected device.id & product.name, now I want to insert this data into my existing device table using device.id.
I want to insert multiple dropdown values in my database. Can anyone tell me how can I solve this problem? Below is my Controller Code-
foreach ($request->all() as $value)
{
$deviceById= Device::find($request->id);
if($request->destination_type == 'dealer')
{
$deviceById->destination_location=$value->dealer_id;
}else
{
$deviceById->destination_location=$value->office_id;
}
$deviceById->save();
}
flash('Device Dispatch added successfully!')->success()->important();
return redirect()->back();
You can make array of all dropdowns value and convert into a json string and store it in database
You can do something like this. Change according to your requirement. It just a logic demo.
$deviceById= Device::find($request->id);
$destination = array();
foreach ($request->all() as $value)
{
if($request->destination_type == 'dealer')
{
$destination[] = $value->dealer_id;
}else
{
$destination[] = $value->office_id;
}
}
$jsonString = json_encode($destination);
$deviceById->destination_location = $jsonString
$deviceById->save();
flash('Device Dispatch added successfully!')->success()->important();
return redirect()->back();
I solve it this way.I had used Elequent ORM
if($request->destination_type == 'Dealer')
{
DB::table('devices')
->whereIn('id',$request->device_list)
->update(['dealer_id'=>$request->destination_location,'device_status'=>"Dispatch"]);
flash('Device Dispatch dealer added successfully!')->success()->important();
}else
{
DB::table('devices')
->whereIn('id',$request->device_list)
->update(['office_id'=>$request->destination_location,'device_status'=>"Dispatch"]);
flash('Device Dispatch office added successfully!')->success()->important();
}

Logic error when add tag for post in Laravel

I trying function add tag for post in laravel. This is update code:
public function update(PostRequest $request, $id)
{
$post = Post::find($id);
$post->update($request->all());
if ($request->tags) {
$tagNames = explode(',', $request->tags);
$tagIds = [];
foreach ($tagNames as $tagName) {
$tagCount = Tag::where('name', '=', $tagName)->count();
if ($tagCount < 1) {
$tag = $post->tags()->create(['name' => $tagName]);
} else {
$post->tags()->detach();
$tag = Tag::where('name', $tagName)->first();
}
$tagIds[] = $tag->id;
}
$post->tags()->sync($tagIds);
}
return back()->with('success', 'Successfully');
}
It works well with pivot table, this has been resolved.
My problem lies in the tag table. When I delete all tags and retype new tag or exist tag, ok it works.
But when I do not change or keeping old tag and continue add new tag will cause an logic error. It will automatically add the record to the tags table.
For example: my post has 3 tags: test1, test2, test3. I keep it and add a tag: test4 then in the table tag automatically add tag: test2, test3, test4.
Is there a solution to my problem? Where was I wrong? I spent almost 2 days for it. I don't want to use package. Vote up for answer useful.
First, use firstOrCreate, it is short and convenient. Then, don't detach, it is useless, sync makes connected tags just like the array tagIds, it removes non-existing elements out of a pivot table and adds new ones.
In addition, you have spaces between commas and words, so you need to trim it.
if ($request->tags) {
$tagNames = explode(',', $request->tags);
$tagIds = [];
foreach ($tagNames as $tagName) {
$tag = Tag::firstOrCreate(['name' => trim($tagName)]);
$tagIds[] = $tag->id;
}
$post->tags()->sync($tagIds);
}
I think I've understood your bug, it is here
if ($tagCount < 1) {
$tag = $post->tags()->create(['name' => $tagName]);
} else {
$post->tags()->detach();
$tag = Tag::where('name', $tagName)->first();
}
It means that when you pass a new tag, it removes all the related tags out of the post. If you pass only old tags, they are not removed.

How do I split my HABTM tags?

I want to take a field in the add form of the Post, explode it at the spaces, and save each word as a Tag, which HasAndBelongsToMany Post. So, for each unrecognized tag, it will create a new one, but if the Tag already exists, it will only create a new reference in the posts_tags tables. I've tried using saveAll, saveAssociated, and few foreach hacks, and I am not exactly sure where it went wrong, but I cannot figure out how to save the associate data. Any sort of outline of how to get the tag data from the form to the database would be appreciated.
//in model
public function parseTags($data) {
$str = $data['Tag'][0]['title'];
$tags = explode('',$str);
for ($i=0; $i<count($tags); $i++) {
$data['Tag'][$i]['title'] = $tags[$i];
}
return $data;
}
//in view
echo $this->Form->input('Tag.0.title',array('label'=>'Tags'));
//in controller
public function add() {
if ($this->request->is('post')) {
$this->Question->create();
$this->request->data['Question']['user_id'] = $this->Auth->user('id');
$this->request->data = $this->Question->parseTags($this->request->data);
if ($this->Question->saveAll($this->request->data)) {
$this->Session->setFlash(__('The question has been saved'), 'default', array('class' => 'success'));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The question could not be saved. Please, try again.'));
}
}
$users = $this->Question->User->find('list');
$this->set(compact('users'));
}
You must first check if Tag saved before or not, if not saved, You can save it. So before you save your model ,all of your tags is saved before.
something like this:
/* $tag_list is exploded tags*/
foreach ($tag_list as $tag) {
$res = $this->Tag->find('first', array('conditions' => array('Tag.name' => $tag)));
if ($res != array()) {
$tag_info[] = $res['Tag']['id'];
} else {
$this->Tag->create();
$this->Tag->save(array('Tag.name' => $tag));
$tag_info[] = sprintf($this->Tag->getLastInsertID());
}
}
$this->model->data['Tag']['Tag'] = $tag_info;

Starting new query context in CodeIgniter's Active Record

I basically wanna do what I'd call nested queries (but not in the nested SELECT way) using CodeIgniter's Active Record.
So it would be like putting aside the current AR context to run a new query before restoring it.
A concrete example:
function handle_form($fields, $POST)
{
foreach ($fields as $field)
{
if ($field->type == "file")
do_upload($field->post); //This function does insert data in another table using AR too
$this->db->set($field->name, $POST[$field->post]);
}
$this->db->insert('table');
}
I haven't found any resources about that, maybe I'm just using the wrong keywords..
Thanks for your help !
function handle_form($fields, $POST)
{
$data = array();
foreach ($fields as $field)
{
if ($field->type == "file")
do_upload($field->post);
$data[$field->name] = $POST[$field->post];
}
$this->db->insert('table', $data);
}

Magento saving multiselect in controller?

$fieldset->addField('brand_id', 'multiselect', array(
'label' => Mage::helper('expertbrand')->__('Merk:'),
'name' => 'brand_id[]',
'values' => $aOptionsMerk,
));
I have this multiselect box with some 600 options. I would like to know how to save this in the controller?
I have tried everything and worked on this problem for 3 days now. Also on the internet I cannot find a correct anwser to this problem. Hoping someone here is able to help me because I'd really like to know!
My controller code:
public function saveAction() {
if ($data = $this->getRequest()->getPost()) {
if(isset($_FILES['filename']['name']) && $_FILES['filename']['name'] != '') {
try {
/* Starting upload */
$uploader = new Varien_File_Uploader('filename');
// Any extention would work
$uploader->setAllowedExtensions(array('jpg','jpeg','gif','png'));
$uploader->setAllowRenameFiles(false);
// Set the file upload mode
// false -> get the file directly in the specified folder
// true -> get the file in the product like folders
// (file.jpg will go in something like /media/f/i/file.jpg)
$uploader->setFilesDispersion(false);
// We set media as the upload dir
$path = Mage::getBaseDir('media') . DS ;
$uploader->save($path, $_FILES['filename']['name'] );
} catch (Exception $e) {
}
//this way the name is saved in DB
$data['filename'] = $_FILES['filename']['name'];
}
/*
$brands=$data['brand_id'];
$t=count($brands);
$inhoud="";
$i=1;
foreach ($brands as $brand){
if ($t == $i){
$inhoud.=$brand;
} else {
$inhoud.=$brand." , ";
}
$i++;
}
//echo $inhoud;
// $br=array('brand_id');
$br=$inhoud;
$data['brand_id']=$br;
*/
//hier moet de loop komen
$id= $data['expert_id'];
$db1 = Mage::getSingleton('core/resource')->getConnection('core_write');
$result = $db1->query("SELECT name FROM expert where expert_id=$id");
$rows = $result->fetch(PDO::FETCH_ASSOC);
$data['name']=$rows['name'];
//$data['brand_id']=$_POST['brand_id'];
$model = Mage::getModel('expertbrand/expertbrand');
$model->setData($data)
->setId($this->getRequest()->getParam('id'));
try {
if ($model->getCreatedTime == NULL || $model->getUpdateTime() == NULL) {
$model->setCreatedTime(now())
->setUpdateTime(now());
} else {
$model->setUpdateTime(now());
}
$model->save();
//hier is het einde van de loop..
Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('expertbrand')->__('Item was successfully saved'));
Mage::getSingleton('adminhtml/session')->setFormData(false);
if ($this->getRequest()->getParam('back')) {
$this->_redirect('*/*/edit', array('id' => $model->getId()));
return;
}
$this->_redirect('*/*/');
return;
} catch (Exception $e) {
Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
Mage::getSingleton('adminhtml/session')->setFormData($data);
$this->_redirect('*/*/edit', array('id' => $this->getRequest()->getParam('id')));
return;
}
}
Mage::getSingleton('adminhtml/session')->addError(Mage::helper('expertbrand')->__('Unable to find item to save'));
$this->_redirect('*/*/');
}
How should I save the optionsArray that is sent through the $_POST? Thanks in advance.
Add this to your saveAction in your Controller to convert the data to a string:
foreach ($data as $key => $value)
{
if (is_array($value))
{
$data[$key] = implode(',',$this->getRequest()->getParam($key));
}
}
To start:
You've declared the input as "brand_id[]", so you are looking for $data['brand_id'], which should be an array. In the commented code, you appear to use that data, but your current code only looks for $data['expert_id'], which doesn't seem to be the same thing.
Even if you change that line to $data['brand_id'], keep in mind that it is an array, so you'll need to be cognizant of that in queries.
You've got a bunch of logic in the controller that doesn't belong there. In an MVC app (of which Magento is a canonical example), most of that SQL logic (as well as the createdtime/updatedtime stuff) belongs in the model (probably expertbrand/expertbrand).
It's not clear how you defined expertbrand/expertbrand. Is this an EAV model? What is its definition? This is most likely the root of your problem, as you have to tell Magento about your EAV model for it to save like that.
Please fix those things (and clarify on the model code) and we can debug further if necessary.
Thanks,
Joe
its clear to me that the data is sent in an array. In order to fix that i created function that rewrites the array.
$brands=$data['brand_id'];
$t=count($brands);
$inhoud="";
$i=1;
foreach ($brands as $brand){
if ($t == $i){
$inhoud.=$brand;
}
else {
$inhoud.=$brand." , ";
}
$i++;
}
//echo $inhoud;
// $br=array('brand_id');
$br=$inhoud;
$data['brand_id']=$br;
the DATA saved in the database would look something like this:
104 , 106 , 107 , 108
i do this cos i read somewhere that this was necessary to do so.
How ever when i open my edit field the only one which shows :
selected="selected" is the brand with the value 108 (the last one)
this is a problem because i need all 4 of them to be shown as selected.
Has this something to do in the way how i save this data ...not sure if the data should be saved as an array to show all selected="selected" fields in the edit
by the way the expert_id is something else and not an issue here i know the sql should be somewhere else but since i am still learning magento this was a quick a dirty method to fix a problem i had earlier...
all i want to know is how to store the array to show all values as an selected="selected" field in the edit form...Txs....
Ok i fixed the problem the data should be saved as
106,108,114,99
now everything is selected in the edit field strange nothing of this is to be found here on the internet hopefully it will be helpfull to other people dealing with the same problem

Resources