$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.
Related
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]);
}
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);
}
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.
I'm working on some e-commerce website based on merchant. There is problem comping in submitting order. the problem is when i'm selecting same merchant that time order will be stored successfully, but when i'm selecting multiple product from different merchant that time my function through error of Undefined offset:1. Here is my function.
public function post_order(){
$data = Input::all();
$count = count($data['invoice_no']);
$order = array();
for($i=0; $i<$count; $i++){
if(!empty($data['invoice_no'][$i])){
array_push($order, array(
'order_no' => $data['order_no'][$i],
'invoice_prefix' => $data['invoice_prefix'][$i],
'invoice_no' => $data['invoice_no'][$i],
'merchant_id' => $data['merchant_id'][$i],
'customer_id' => $data['customer_id'][$i],
'buytokri_order' => $data['order_name'][$i],
'name' => $data['name'][$i],
'pincode' => $data['pincode'][$i],
'address' => $data['address'][$i],
'landmark' => $data['landmark'][$i],
'city' => $data['city'][$i],
'state' => $data['state'][$i],
'country' => $data['country'][$i],
'mobile' => $data['mobile'][$i],
'subtotal' => $data['selling_price'][$i],
'payment_type' => $data['payment_type'][$i],
'txn_id' => $data['txn'][$i],
'shipping' => $data['shipping'][$i],
'total' => $data['subtotal'][$i]
));
}
}
Order::insert($order);
$var = $data['order_no'];
foreach ($var as $vars) {
$id = DB::table('ads_order')->where('order_no', $vars)->get();
}
$count = count($data['invoice_no']);
$orderhistory = array();
for($i=0; $i<=$count; $i++){
if(!empty($data['invoice_no'][$i])){
array_push($orderhistory, array(
'order_id' => $id[$i]->id,
'merchant_id' => $data['merchant_id'][$i],
'customer_id' => $data['customer_id'][$i],
'order_status' => $data['order_status'][$i],
'comment' => $data['comment'][$i],
'notify' => $data['notify'][$i],
'default' => $data['default'][$i],
'status' => $data['status'][$i]
));
}
}
Orderhistory::insert($orderhistory);
return Redirect::intended('/ordersuccess');
}
i have to update a table and change the value inside it and the table have many column inside it. i tried to use query builder and here is my current code
the query is inside the public function ugetstd($id)
public function ugetstd($id) //update
{
$rules = array(
'firstname' => 'required|max:80|regex:/^[\p{L}\p{N} - ]+$/u',
'middlename' => 'required|max:50|regex:/^[\p{L}\p{N} -]+$/u', //more here
);
$messages = array(
'firstname.required' => 'First name is required',
'firstname.max' => 'First name can only contain 80 characters' //more here
);
$validator = Validator::make(Input::all(), $rules, $messages);
if ($validator->fails())
{
return Redirect::to('view_students/' . $id)
->withErrors($validator)
->withInput(Input::except('password'));
}
else
{
DB::table('dbo_students')->where('StudentID', $id )
->update
(
array
(
'FirstName' => Input::get('firstname'),
'MiddleName' => Input::get('middlename'),
'LastName' => Input::get('lastname'),
'CurrentStatusID' => Input::get('scs'),
'Sex' => Input::get('sex'),
'ReligionID' => Input::get('rel'),
'EthnicityID' => Input::get('eth'),
'StreetAddress' => $enAdd,
'CityID' => Input::get('city'),
'YearLevelID' => Input::get('yearlevel'),
'Telephone' => Input::get('telephone'),
'Birthdate' => Input::get('date'),
'Birthplace' => Input::get('birthplace'),
'SchoolLastAttended' => Input::get('schoollastattended'),
'LastGradeCompleted' => Input::get('lastgradecompleted'),
'CurrentModuleLeft' => Input::get('currentmoduleleft'),
'CurrentModuleCriticalLevel' => Input::get('modulecriticallevel'),
'StudentDescription' => Input::get('description')
)
);
return Redirect::to('view_students/' . $id);
}
}
the thing is it does not execute the code. it does not update anything and it does not throw any error. any ideas what i am doing wrong? thanks