Importing to 'users' table but also imports to pivot tables - laravel

I am able to import for 'users' table but I also need to import to pivot tables. Here's my code from my UsersController for importing to 'users' table, but is it possible to supply data to pivot tables like "user_company", "user_department" by importing? Can you show me a sample of importing to pivot tables? Anyways this is my code in importing.
if( Input::file('file_import') ) {
$path = Input::file('file_import')->getRealPath();
$inserts = [];
Excel::load($path,function($reader) use (&$inserts)
{
foreach ($reader->toArray() as $row){
$inserts[] = ['email' => $row['email'], 'username' => $row
['username'], 'password' => $row['password'], 'first_name' => $row['first_name'],'middle_name' => $row['middle_name'], 'last_name' => $row['last_name'], 'gender' => $row['gender'],
'civil_status' => $row['civil_status'], 'spouse' => $row['spouse'], 'religion' => $row['religion'],'emergency_no' => $row['emergency_no'],'previous_work' => $row['previous_work'],
'remarks' => $row['remarks'],'course' => $row['course'],'biometrics' => $row['biometrics'],'immediate_head' => $row['immediate_head'],'designation' => $row['designation'],'level' => $row['level'],
'emp_status' => $row['emp_status'],'dependents' => $row['dependents'],'date_hired' => $row['date_hired'],'regularization_date' => $row['regularization_date'],'remmitance_date' => $row['remmitance_date'],
'tin' => $row['tin'],'philhealth' => $row['philhealth'],'pagibig' => $row['pagibig'],'sss' => $row['sss'],'umid' => $row['umid'],'phone' => $row['phone'],'avatar' => $row['avatar'],
'address' => $row['address'],'country_id' => $row['country_id'],'role_id' => $row['role_id'],'birthday' => $row['birthday'],'status' => $row['status']];
}
});
}
}
if (!empty($inserts)) {
DB::table('users')->insert($inserts);
return back()->with('success','Inserted Record successfully');
}

There is a better way for this case, using Laravel Eloquent Relationships, but when using Laravel Database Query Builder you should get the last inserted id and to use it in next insert in "user_company", "user_department".
$userinsert = DB::table('users')->insert($inserts);
$insertedId = $userinsert->id;
$insertsusercompany = [
'user_id' => $insertedId,
'value1' => 'somedata1',
'value2' => 'somedata2'
]
$usercompany = DB::table('user_company')->insert($insertsusercompany);
... and the same for others tables, but you should use Eloquent Relationships, because it is much more easier.

Related

I cant get lastInsertId on laravel 7 project

$sql = DB::table('laravel_products')
->insert(array(
'name' => $name,
'price' => $price,
'qty' => $qty,
'description' => $description,
'uruu' => $uruu,
'garage' => $garage,
'duureg' => $duureg,
'tagt' => $tagt,
'talbai' => $talbai,
'haalga' => $haalga,
'tsonh' => $tsonh,
'shal' => $shal,
'tsonhtoo' => $ttsonh,
'hdawhar' => $bdawhar,
'lizing' => $lizing,
'utas' => $utas,
'email' => $email,
'hereg' => $hereg,
'bairshil' => $bairshil,
'bairlal' => $bairlal,
'ashig' => $ashigon,
'zahi' => $zahi,
'image' => $data
));
$lastInsertedID = $sql->lastInsertId();
When I try to insert its responses:
"Call to a member function lastInsertId() on bool"
I used insertGetId but its cant save multiple rows of pictures on mysql.
If you want to get the last inserted ID like that you can call that method on the PDO instance directly:
$id = DB::getPdo()->lastInsertId();
If the table has an auto-incrementing id, use the insertGetId method to insert a record and then retrieve the ID:
$id = DB::table('users')->insertGetId(
['email' => 'john#example.com', 'votes' => 0]
);
from : https://laravel.com/docs/5.8/queries#inserts
$data = new LaravelProducts(); //LaravelProducts is your Model Name
$data->name= $name; //here 'name' is your column name
$data->price= $price; //here 'price' is your column name
$data->qty= $qty; //here 'qty' is your column name
$data->description= $description; //here 'description' is your column name
..........
..........
$data->image= $image; //here 'image' is your column name
$data->save();
$lastInsertedId = $data->id;
You don't have to write a new query to collect last inserted id from database.
$laravel_product = DB::table('laravel_products')
->insertGetId( array(
'name' => $name,
'price' => $price,
'qty' => $qty,
'description' => $description,
'uruu' => $uruu,
'garage' => $garage,
'duureg' => $duureg,
'tagt' => $tagt,
'talbai' => $talbai,
'haalga' => $haalga,
'tsonh' => $tsonh,
'shal' => $shal,
'tsonhtoo' => $ttsonh,
'hdawhar' => $bdawhar,
'lizing' => $lizing,
'utas' => $utas,
'email' => $email,
'hereg' => $hereg,
'bairshil' => $bairshil,
'bairlal' => $bairlal,
'ashig' => $ashigon,
'zahi' => $zahi,
'image' => $data
)
);
foreach ($filenamesToSave as $filename) {
DB::insert('INSERT INTO laravel_products_images ( product_id, filename ) VALUES ( ?, ? )',[$laravel_product->id, $filename]);
return view('createproduct');
} // Foreach Closing
// Echo your inserted ID Like Below
echo $laravel_product->id;
It should be 100% working for you.

How to update data in database using import excel laravel if any data exist

how to update data in database with import excel if data exist just update, and if not exist just save. i am using laravel 5.8 and maatwebsite 2.1
this is my controller :
$request->validate([
'file' => 'required|mimes:csv,xls,xlsx',
'divisi' => 'required',
'file_type' => 'required'
]);
$path = $request->file('file')->getRealPath();
$data = Excel::load($path)->first();
$divisi = $request->input('divisi');
$file_type = $request->input('file_type');
if(!empty($data) && $data->count()){
foreach ($data as $key => $value) {
$arr[] = [
'product_id' => $value->product_id,
'upc' => $value->upc,
'desc_a' => $value->desc_a,
'name' => $value->name,
'category' => $value->category,
'desc_b' => $value->desc_b,
'desc_c' => $value->desc_c,
'desc_d' => $value->desc_d,
'desc_e' => $value->desc_e,
'desc_f' => $value->desc_f,
'desc_g' => $value->desc_g,
'desc_h' => $value->desc_h,
'fixel_id' => $value->fixel_id,
'x' => $value->x,
'cost' => $value->cost,
'price' => $value->price,
'reg_movement' => $value->reg_movement,
'total_facings' => $value->total_facings,
'total_units' => $value->total_units,
'days_of_supply' => $value->days_of_supply,
'desc_i' => $value->desc_i,
'kode_lokasi' => $value->kode_lokasi,
'created_by' => Auth::user()->id,
'updated_by' => Auth::user()->id,
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s'),
'divisi' => $divisi,
'file_type' => $file_type];
}
if(!empty($arr)){
Planogram::updateOrCreate($arr);
} }
from this code my data always multiply with same record.
thank you
Done, just change to this
if($data->count()){
foreach ($data as $key => $value) {
$getsku = PlanogramTemp::updateOrCreate([
'desc_b' => $value->desc_b,
'desc_e' => $value->desc_e
],[
'product_id' => $value->product_id,
'upc' => $value->upc,
'desc_a' => $value->desc_a,
'name' => $value->name,
'category' => $value->category,
'desc_b' => $value->desc_b,
'desc_c' => $value->desc_c,
'desc_d' => $value->desc_d,
'desc_e' => $value->desc_e,
'desc_f' => $value->desc_f,
'desc_g' => $value->desc_g,
'desc_h' => $value->desc_h,
'fixel_id' => $value->fixel_id,
'x' => $value->x,
'cost' => $value->cost,
'price' => $value->price,
'reg_movement' => $value->reg_movement,
'total_facings' => $value->total_facings,
'total_units' => $value->total_units,
'days_of_supply' => $value->days_of_supply,
'desc_i' => $value->desc_i,
'kode_lokasi' => $value->kode_lokasi,
'created_by' => Auth::user()->id,
'updated_by' => Auth::user()->id,
'divisi' => $divisi,
'file_type' => $file_type]);
}

Insert data in 2 tables with the last inserted ID of the parent table must also be inserted in the child table

I tried with the code below. The record is inserted but the parent ID is not.
The last inserted ID of the parent table must also be inserted in the child table the same time when submit button is clicked.
Thanks.
Controller:
public function insert_doc_control_review(Request $request)
{
$form_data = array(
'comment' => $request->comment,
'assigned_to' => $request->assigned_to,
'revision' => $request->revision,
'file_id' => $request->file_id,
'attachment' => $request->attachment,
'phase_id' => $request->phase_id,
'review_date' => $request->review_date,
'due_date' => $request->due_date,
'completed_date' => $request->completed_date,
'user_id' => Auth::user()->id,
'doc_number' => $this->getNextDocRevNumber()
);
DocumentControlReview::create($form_data);
$lastId = DocumentControlReview::create($form_data);
$archive_data = array(
'user_id' => Auth::user()->id,
'iso_management_id' => $request->iso_management_id,
'phase_id' => $request->phase_id,
'document_control_review_id' => $request->document_control_review_id,
'initial_approval_id' => $request->initial_approval_id,
'review_id' => $request->review_id,
'final_approval_id' => $request->final_approval_id,
'awaiting_release_id' => $request->awaiting_release_id,
'release_id' => $request->release_id,
'project_id' => $request->project_id,
'folder_id' => $request->folder_id,
'file_id' => $request->file_id,
$lastId
);
DocumentRecordArchive::create($archive_data);
}
You have to write the code like below.
public function insert_doc_control_review(Request $request)
{
$form_data = array(
'comment' => $request->comment,
'assigned_to' => $request->assigned_to,
'revision' => $request->revision,
'file_id' => $request->file_id,
'attachment' => $request->attachment,
'phase_id' => $request->phase_id,
'review_date' => $request->review_date,
'due_date' => $request->due_date,
'completed_date' => $request->completed_date,
'user_id' => Auth::user()->id,
'doc_number' => $this->getNextDocRevNumber()
);
$lastId = DocumentControlReview::create($form_data);
$archive_data = array(
'user_id' => Auth::user()->id,
'iso_management_id' => $request->iso_management_id,
'phase_id' => $request->phase_id,
'document_control_review_id' => $lastId->id, // Parent ID
'initial_approval_id' => $request->initial_approval_id,
'review_id' => $request->review_id,
'final_approval_id' => $request->final_approval_id,
'awaiting_release_id' => $request->awaiting_release_id,
'release_id' => $request->release_id,
'project_id' => $request->project_id,
'folder_id' => $request->folder_id,
'file_id' => $request->file_id,
//'parent_id' => $lastId->id, there is document_control_review_id which I assume is the parent_id foreign column.
);
DocumentRecordArchive::create($archive_data);
}
look lastId is an object which holds the newly created data. you want to add this one's id in the child table. so use it's id attribute. i used parent_id as column name, change it according to your column name.
In case you have well formed relations in both models, another way can be:
$formData = [
'comment' => $request->comment,
'assigned_to' => $request->assigned_to,
'revision' => $request->revision,
'file_id' => $request->file_id,
'attachment' => $request->attachment,
'phase_id' => $request->phase_id,
'review_date' => $request->review_date,
'due_date' => $request->due_date,
'completed_date' => $request->completed_date,
'user_id' => Auth::id(),
'doc_number' => $this->getNextDocRevNumber(),
];
$documentControlReview = DocumentControlReview::create($formData);
$archiveData = [
'user_id' => Auth::id(),
'iso_management_id' => $request->iso_management_id,
'phase_id' => $request->phase_id,
'document_control_review_id' => $request->document_control_review_id,
'initial_approval_id' => $request->initial_approval_id,
'review_id' => $request->review_id,
'final_approval_id' => $request->final_approval_id,
'awaiting_release_id' => $request->awaiting_release_id,
'release_id' => $request->release_id,
'project_id' => $request->project_id,
'folder_id' => $request->folder_id,
'file_id' => $request->file_id,
];
$documentControlReview->documentRecordArchive()->create(archiveData);
For this working you need to have:
// DocumentControlReview::class
public function documentRecordArchive
{
return $this->hasOne(DocumentRecordArchive::class, 'parent_id');
}
// or
public function documentRecordArchives
{
return $this->hasMany(DocumentRecordArchive::class, 'parent_id');
}
// one of these two regarding which relation is set in business model 1:n or m:n
// DocumentRecordArchive::class
public function documentControlReview()
{
return $this->belongsTo(DocumentControlReview::class, 'parent_id');
}
Also, if child record in DB is mandatory, it is smart to set all transactions into try catch block:
try {
\DB::beginTransaction();
// make parent insertion
// make child insertion
// make another related DB actions if needed
// all good
\DB::commit();
} catch (\Exception $e) {
// nothing will be applied, something went wrong with one DB transaction
\DB::rollback();
// return redirect()->back()->with('error', $e->getMessage());
}
What is main thing I want to point here is that you don't need to use parentId value in array of child's data because it will be recognised as well and it is in some hand more secure - there is no way wrong parentId would be applied.
$firstTransaction->relationFromModel()->create($dataWithoutFirstTransactionIdBecauseItIsAlreadyAppliedThisWay);
Try this
public function insert_doc_control_review(Request $request)
{
$form_data = array(
'comment' => $request->comment,
'assigned_to' => $request->assigned_to,
'revision' => $request->revision,
'file_id' => $request->file_id,
'attachment' => $request->attachment,
'phase_id' => $request->phase_id,
'review_date' => $request->review_date,
'due_date' => $request->due_date,
'completed_date' => $request->completed_date,
'user_id' => Auth::user()->id,
'doc_number' => $this->getNextDocRevNumber()
);
$lastId = DocumentControlReview::create($form_data);
$archive_data = array(
'user_id' => Auth::user()->id,
'iso_management_id' => $request->iso_management_id,
'phase_id' => $request->phase_id,
'initial_approval_id' => $request->initial_approval_id,
'review_id' => $request->review_id,
'final_approval_id' => $request->final_approval_id,
'awaiting_release_id' => $request->awaiting_release_id,
'release_id' => $request->release_id,
'project_id' => $request->project_id,
'folder_id' => $request->folder_id,
'file_id' => $request->file_id,
'document_control_review_id' => $lastId->id
);
DocumentRecordArchive::create($archive_data);
}

Using isDirty in Laravel

I'm using the isDirty() method in my controller to check if any field is changed. Then I am saving the old data of a field and the new data in a table. The code is working fine; however, how can I optimize this code?
By using the below code, I will have to write each field name again and again. If request->all() has 20 fields, but I want to check six fields if they are modified, how can I pass only 6 fields in the below code, without repeating?
Controller
if ($teacher->isDirty('field1')) {
$new_data = $teacher->field1;
$old_data = $teacher->getOriginal('field1');
DB::table('teacher_logs')->insert(
[
'user_id' => $user->id,
'teacher_id' => $teacher->id,
'old_value' => $old_data,
'new_value' => $new_data,
'column_changed' => "First Name",
]);
}
You can set a list of what fields you want to be checking for then you can loop through the dirty fields and build your insert records.
use Illuminate\Support\Arr;
...
$fields = [
'field1' => 'First Name',
'field2' => '...',
...
];
$dirtied = Arr::only($teacher->getDirty(), array_keys($fields));
$inserts = [];
foreach ($dirtied as $key => $value) {
$inserts[] = [
'user_id' => $user->id,
'teacher_id' => $teacher->id,
'old_value' => $teacher->getOriginal($key),
'new_value' => $value,
'column_changed' => $fields[$key];
];
}
DB::table(...)->insert($inserts);
i tried following code after getting idea by lagbox in comments, and i have found solution to my problem.
$dirty = $teacher->getDirty('field1','field2','field3');
foreach ($dirty as $field => $newdata)
{
$olddata = $teacher->getOriginal($field);
if ($olddata != $newdata)
{
DB::table('teacher_logs')->insert(
['user_id' => $user->id,
'teacher_id' => $teacher->id,
'old_value' => $olddata,
'new_value' => $newdata,
'column_changed' => "changed",
]);
}
}

Importing excel has an error of "Illegal string offset" in my controller

I'm trying to import an excel to my database table 'users' but it has an error saying Illegal string offset "email". I tried deleting the "email" then it says that Illegal string offset "username" now. Is it really the error in controller? Or maybe the reason is that i also have a repository.
This is my code for the controller
public function userImport()
{
if( Input::file('file_import') ) {
$path = Input::file('file_import')->getRealPath();
$inserts = [];
Excel::load($path,function($reader) use (&$inserts)
{
foreach ($reader->toArray() as $rows){
foreach($rows as $row){
$inserts[] = ['email' => $row['email'], 'username' => $row
['username'], 'password' => $row['password'], 'first_name' => $row['first_name'],'middle_name' => $row['middle_name'], 'last_name' => $row['last_name'], 'gender' => $row['gender'],
'civil_status' => $row['civil_status'], 'spouse' => $row['spouse'], 'religion' => $row['religion'],'emergency_no' => $row['emergency_no'],'previous_work' => $row['previous_work'],
'remarks' => $row['remarks'],'course' => $row['course'],'biometrics' => $row['biometrics'],'immediate_head' => $row['immediate_head'],'designation' => $row['designation'],'level' => $row['level'],
'emp_status' => $row['emp_status'],'dependents' => $row['dependents'],'date_hired' => $row['date_hired'],'regularization_date' => $row['regularization_date'],'remmitance_date' => $row['remmitance_date'],
'tin' => $row['tin'],'philhealth' => $row['philhealth'],'pagibig' => $row['pagibig'],'sss' => $row['sss'],'umid' => $row['umid'],'phone' => $row['phone'],'avatar' => $row['avatar'],
'address' => $row['address'],'country_id' => $row['country_id'],'role_id' => $row['role_id'],'birthday' => $row['birthday'],'status' => $row['status']];
}
}
});
}
if (!empty($inserts)) {
DB::table('users')->insert($inserts);
return back()->with('success','Inserted Record successfully');
}
return back();
}
As per your dumped $rows, it looks like that you don't need another foreach inside another foreach, modify your code.
// readability purpose
$rows = $reader->toArray();
foreach ($rows as $row){
$inserts[] = ['email' => $row['email'], 'username' => $row
['username'], 'password' => $row['password'], 'first_name' => $row['first_name'],'middle_name' => $row['middle_name'], 'last_name' => $row['last_name'], 'gender' => $row['gender'],
'civil_status' => $row['civil_status'], 'spouse' => $row['spouse'], 'religion' => $row['religion'],'emergency_no' => $row['emergency_no'],'previous_work' => $row['previous_work'],
'remarks' => $row['remarks'],'course' => $row['course'],'biometrics' => $row['biometrics'],'immediate_head' => $row['immediate_head'],'designation' => $row['designation'],'level' => $row['level'],
'emp_status' => $row['emp_status'],'dependents' => $row['dependents'],'date_hired' => $row['date_hired'],'regularization_date' => $row['regularization_date'],'remmitance_date' => $row['remmitance_date'],
'tin' => $row['tin'],'philhealth' => $row['philhealth'],'pagibig' => $row['pagibig'],'sss' => $row['sss'],'umid' => $row['umid'],'phone' => $row['phone'],'avatar' => $row['avatar'],
'address' => $row['address'],'country_id' => $row['country_id'],'role_id' => $row['role_id'],'birthday' => $row['birthday'],'status' => $row['status']];
}
$rows already represents each row, so you should probably rename it to $row.

Resources