Laravel, multiple file deleting in foreach - laravel

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

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

save array in controller 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();
}

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();
}

How to insert big data on the laravel?

I am using laravel 5.6
My script to insert big data is like this :
...
$insert_data = [];
foreach ($json['value'] as $value) {
$posting_date = Carbon::parse($value['Posting_Date']);
$posting_date = $posting_date->format('Y-m-d');
$data = [
'item_no' => $value['Item_No'],
'entry_no' => $value['Entry_No'],
'document_no' => $value['Document_No'],
'posting_date' => $posting_date,
....
];
$insert_data[] = $data;
}
\DB::table('items_details')->insert($insert_data);
I have tried to insert 100 record with the script, it works. It successfully insert data
But if I try to insert 50000 record with the script, it becomes very slow. I've waited about 10 minutes and it did not work. There exist error like this :
504 Gateway Time-out
How can I solve this problem?
As it was stated, chunks won't really help you in this case if it is a time execution problem. I think that bulk insert you are trying to use cannot handle that amount of data , so I see 2 options:
1 - Reorganise your code to properly use chunks, this will look something like this:
$insert_data = [];
foreach ($json['value'] as $value) {
$posting_date = Carbon::parse($value['Posting_Date']);
$posting_date = $posting_date->format('Y-m-d');
$data = [
'item_no' => $value['Item_No'],
'entry_no' => $value['Entry_No'],
'document_no' => $value['Document_No'],
'posting_date' => $posting_date,
....
];
$insert_data[] = $data;
}
$insert_data = collect($insert_data); // Make a collection to use the chunk method
// it will chunk the dataset in smaller collections containing 500 values each.
// Play with the value to get best result
$chunks = $insert_data->chunk(500);
foreach ($chunks as $chunk)
{
\DB::table('items_details')->insert($chunk->toArray());
}
This way your bulk insert will contain less data, and be able to process it in a rather quick way.
2 - In case your host supports runtime overloads, you can add a directive right before the code starts to execute :
ini_set('max_execution_time', 120 ) ; // time in seconds
$insert_data = [];
foreach ($json['value'] as $value)
{
...
}
To read more go to the official docs
It makes no sense to use an array and then convert it to a collection.
We can get rid of arrays.
$insert_data = collect();
foreach ($json['value'] as $value) {
$posting_date = Carbon::parse($value['Posting_Date']);
$posting_date = $posting_date->format('Y-m-d');
$insert_data->push([
'item_no' => $value['Item_No'],
'entry_no' => $value['Entry_No'],
'document_no' => $value['Document_No'],
'posting_date' => $posting_date,
....
]);
}
foreach ($insert_data->chunk(500) as $chunk)
{
\DB::table('items_details')->insert($chunk->toArray());
}
Here is very good and very Fast Insert data solution
$no_of_data = 1000000;
$test_data = array();
for ($i = 0; $i < $no_of_data; $i++){
$test_data[$i]['number'] = "1234567890";
$test_data[$i]['message'] = "Test Data";
$test_data[$i]['status'] = "Delivered";
}
$chunk_data = array_chunk($test_data, 1000);
if (isset($chunk_data) && !empty($chunk_data)) {
foreach ($chunk_data as $chunk_data_val) {
DB::table('messages')->insert($chunk_data_val);
}
}
I used the code below to check the update or insert data of 11 thousand rows. I hope it useful for you.
$insert_data = [];
for ($i=0; $i < 11000; $i++) {
$data = [
'id' =>'user_'.$i,
'fullname' => 'Pixs Nguyen',
'username' => 'abc#gmail.com',
'timestamp' => '2020-03-23 08:12:00',
];
$insert_data[] = $data;
}
$insert_data = collect($insert_data); // Make a collection to use the chunk method
// it will chunk the dataset in smaller collections containing 500 values each.
// Play with the value to get best result
$accounts = $insert_data->chunk(500);
// In the case of updating or inserting you will take about 35 seconds to execute the code below
for ($i=0; $i < count($accounts); $i++) {
foreach ($accounts[$i] as $key => $account)
{
DB::table('yourTable')->updateOrInsert(['id'=>$account['id']],$account);
}
}
// In the case of inserting you only take about 0.35 seconds to execute the code below
foreach ($accounts as $key => $account)
{
DB::table('yourTable')->insert($account->toArray());
}

codeigniter generating multiple pdfs

i'm trying to generates pdfs in loop against member id, but every time i got only the first one, i addedd code in foreach so it runs multiple times, but it gives me only one pdf.please someone help me.
public function pdf($ids){
$k = 0;
foreach ($ids as $key => $id) {
$data[$k]['academics'] = $this->Utility_model->get_all_from_table_where('member_academics', array('member_id' => $id));
$data[$k]['member_employment'] = $this->Utility_model->get_all_from_table_where('member_employment', array('member_id' => $id));
$data[$k]['member_data'] = $this->Utility_model->get_all_from_table_where('members',array('member_id' => $id));
$data[$k]['disclosure'] = $this->Utility_model->get_all_from_table('generalsettings',array('key'=>'disclosure'));
$data[$k]['enrollment_fee'] = $this->Utility_model->get_all_from_table('member_invoices',array('user_id' => $id,'paymentFor'=>'Enrollment Fee'));
$data[$k]['enrollment_fee']['payment'] = $this->Utility_model->get_all_from_table('member_payments',array('invoice_id'=>$data[$k]['enrollment_fee']['id']));
$j=0;
if (!empty($data[$k]['member_data'])) {
foreach ($data[$k]['member_data'] as $member) {
$data[$k]['member_data'][$j]['term'] = $this->Utility_model->get_all_from_table('term', array('term_id' => $member['term_id']));
$data[$k]['member_data'][$j]['degree'] = $this->Utility_model->get_all_from_table('degree', array('degree_id' => $member['degree_id']));
$data[$k]['member_data'][$j]['year'] = $this->Utility_model->get_all_from_table('year', array('year_id' => $member['year_id']));
$data[$k]['member_data'][$j]['address'] = $this->Utility_model->get_all_from_table('member_addresses', array('id' => $member['address_id']));
$j++;
}
}
$this->load->view('admin/reports_management/applications_pdf/pdf_output',$data[$k],false);
$html = $this->output->get_output();
$this->load->library('dompdf_gen');
$this->dompdf->load_html($html);
$this->dompdf->render();
$this->dompdf->stream($k."file".".pdf");
$k++;
}
// echo "<pre>";
// print_r($data);
// die;
}
As long as you only request the page once you cannot get the controller method to output more than one file. You could either try to instead make a multiple page PDF or you need to change how the controller is called, and call it multiple times.
See this answer for some input about making multiple page PDF: How to create several pages with dompdf

Resources