save array in controller laravel - laravel

ErrorException
Array to string conversion
$presocio = new Presocio;
$presocio->prestamo_id = $request->prestamo_id;
$presocio->ncuota = $request->ncuota;
$presocio->montopag = $request->montopag;
$presocio->fechapag = $request->fechapag;
$presocio->save();
In the end I managed to make it work like this, it works perfectly.
it can be done in different ways, example with ::create ::insert
$prestamo = new Prestamo;
$prestamo->socio_id = $request->socio_id;
$prestamo->monto = $request->monto;
$prestamo->cuotas = $request->cuotas;
$prestamo->alias = $request->alias;
$prestamo->save();
$idprestamo = $prestamo->id;
if (count($request->ncuota) > 0) {
foreach ($request->ncuota as $item => $v) {
$presocio = new Presocio;
$presocio->fill(
array(
'prestamo_id' => $idprestamo,
'ncuota' => $request->ncuota[$item],
'montopag' => $request->montopag[$item],
'fechapag' => $request->fechapag[$item],
)
);
$presocio->save();
}
}
toast('Pago Programados Registrado', 'success');
return redirect('prestamo');

Update since we now have the form supplied. You are using form names such as ncuota[] instead of ncuota which makes it an array. Are you able to make more than 1 Preseocio? if this is the case you want to loop over the items in the controller.
for ($i = 0; $i < count($request->ncuota); $i++)
{
Presocio::create([
'prestamo_id' => $request->prestamo_id[$i],
'ncuota' => $request->ncuota[$i],
'montopag' => $request->montopag[$i],
'fechapag' => $request->fechapag[$i],
]);
}
Otherwise just remove the [] off the end of the form names.
class Presocio
{
...
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'prestamo_id',
'ncuota',
'montopag',
'fechapag',
];
...
}
Presocio::create($request->all());
Now, Thats not the issue. That is just a bit of house keeping.
Your issue is that one of your request fields is an Array. Which ever one it is you will need to convert it to a JSON object or find a better way of storing it.
If you dont care and want to keep it as an array, modify the database field to be a jsonb field.

Try This create method
remove your all code and write only this code in your store method
$input = $request->all();
Presocio::create($input);

You can do that like:
for($i=0; $i < count($request->input('prestamo_id', 'ncuota', 'montopag', 'fechapag')); $i++) {
$presocio = new Presocio;
$presocio->prestamo_id = $request->prestamo_id[$i];
$presocio->ncuota = $request->ncuota[$i];
$presocio->montopag = $request->montopag[$i];
$presocio->fechapag = $request->fechapag[$i];
$presocio->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();
}

Laravel, multiple file deleting in foreach

I wanna delete files from server by database ids.
I'm trying to do this in foreach loop.
Single file deleting is ok but, when user sends multiple file (by checkbox)
my loop deletes only first.
public function postSil(Request $request)
{
$ids = $request->input('sil');
foreach($ids as $id)
{
$file = File::find($id)->first();
$path = public_path().'/rea-files/'.$file->rea_number.'/'.$file->file_name;
\File::delete($path);
// echo 'id';
}
//return 1;
File::destroy($ids); //this is model file.
return redirect()->back();
}
As you can see, i tried if foreach loop works as well, placed echo and return and i see foreach loop is working but only deletes first file.
I have solved. I used array in File::delete()
just try below code
(case A) User fields indexed by number 0,1,2..
$users_to_delete = array(
'0'=> array('1','Frank','Smith','Whatever'),
'1'=> array('5','John','Johnson','Whateverelse'),
);
$ids_to_delete = array_map(function($item){ return $item[0]; }, $users_to_delete);
DB::table('users')->whereIn('id', $ids_to_delete)->delete();
//(case B) User fields indexed by key
$users_to_delete = array(
'0'=> array('id'=>'1','name'=>'Frank','surname'=>'Smith','title'=>'Whatever'),
'1'=> array('id'=>'5','name'=>'John','surname'=>'Johnson','title'=>'Whateverelse'),
);
$ids_to_delete = array_map(function($item){ return $item['id']; }, $users_to_delete);
DB::table('users')->whereIn('id', $ids_to_delete)->delete();
Case c
$ids = array( '0' => 1, '1' => 2);
DB::table('users')->whereIn('id',$ids)->delete();

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.

Magento SOAP API Product List Pagination

I'm trying to read the list of products from Magento over the SOAP API (V2) and try to do some/any type of pagination.
Simple scenario:
var filters = new filters();
var products = catalogProductList(out pe, Connection.Session, filters, null);
This crashes Magento with: "Allowed memory size of 1073741824 bytes exhausted (tried to allocate 72 bytes."
I've tried to add pagination by specifying two complex filters on the product_id:
filters.complex_filter = new complexFilter[]
{
new complexFilter()
{
key = "product_id",
value = new associativeEntity()
{
key = "gt",
value = "400"
}
},
new complexFilter()
{
key = "product_id",
value = new associativeEntity()
{
key = "lt",
value = "1000"
}
}
};
However in this scenario only the second filter is applied, the first one is ignored.
I was thinking of reading the category tree and then the assigned products but there are lots of products that are not assigned to any category or to multiple categories so I'll either miss them or get them multiple times.
Is there a way to read the products list using some type of pagination so I don't read the complete list at once?
(Note: Requesting to increase memory is not really an option)
I've come up with a pretty good solution for this. Hope this helps someone.
$in = array();
for ($i = ($page * $size) - $size; $i < ($page * $size); $i++) {
$in[] = $i + 1;
}
$complexFilter = array('complex_filter' =>
array(
array(
'key' => 'product_id',
'value' => array(
'key' => 'in',
'value' => join(",", $in)
)
)
)
);
It looks like the answer you need is described at https://stackoverflow.com/a/22874035/2741137
Apparently, you can capitalize PRODUCT_ID in one of the two filter conditions to work around Magento's limitation that prevents two filter conditions on the same key.
I've successfully done the following in PHP:
$filters = new StdClass();
$filters->complexFilter = array(
array( 'key' =>'sku', 'value' => array('lt'=>'03969999')),
array( 'key' => 'sku', 'value' => array('gt'=>'03969000')),
);
Although, according to
<complexType name="filters"><all><element name="filter" type="typens:associativeArray" minOccurs="0"/><element name="complex_filter" type="typens:complexFilterArray" minOccurs="0"/></all></complexType>
Maybe it needs to be "$filters->complex_filter = array();"? The first code appeared to have worked for me.
Ugly as hell, but works for me :
public catalogProductEntity[] GetProducts()
{
int storeId;
catalogProductEntity[] catalogEntity;
List<catalogProductEntity> res = new List<catalogProductEntity>();
Client.catalogProductCurrentStore(out storeId, SessionId, null);
var filters = new filters();
filters.complex_filter = new complexFilter[1];
filters.complex_filter[0] = new complexFilter();
complexFilter filter = filters.complex_filter[0];
filter.key = "name";
filter.value = new associativeEntity();
associativeEntity assoc = filter.value;
assoc.key = "like";
//A to Z.
for (char i = 'A'; i <= 'Z'; i++)
{
assoc.value = i + "%";
Client.catalogProductList(out catalogEntity, SessionId, filters, null);
res.AddRange(catalogEntity);
}
//Starts with #.
assoc.value = "#%";
Client.catalogProductList(out catalogEntity, SessionId, filters, null);
res.AddRange(catalogEntity);
//0 to 9
for (int i = 0; i <= 9; i++)
{
assoc.value = i + "%";
Client.catalogProductList(out catalogEntity, SessionId, filters, null);
res.AddRange(catalogEntity);
}
return res.ToArray();
}

Resources