codeigniter get last insert id from model to use as redirect parameter - codeigniter

I need to get the insert ID to be used in my controller, the problem is my model function has several data arrays, and I need the insert ID of the 1st array. therefor if I try to get the insert ID on my controller obviously its grabbing the 2nd insert ID and not the 1st.
I'm not sure this makes sense but here is an example:
Model
public function add() {
$data = array(
'name' => $_POST['companyName']
,'type' => $_POST['companyType']
,'active' => '1');
$this->db->insert('company', $data);
$cid = $this->db->insert_id();
$data2 = array(
'cid' => $cid
,'name' => $_POST['locationName']
,'address' => $_POST['locationAddress']);
$this->db->insert('locations', $data2);
}
This is working fine...However after this runs, on my controller the redirect is getting the data2 last insert which makes my redirect wrong.
Controller
public function add() {
if (isset($_POST["add"]))
{
$this->Company_model->add();
$id = $this->db->insert_id();
redirect('company/view/'.$cid);
}
$data['states'] = $this->Company_model->
}
Any help would be greatful!

You were very close. Instead of repeating $id = $this->db->insert_id(); in your controller, you can return the $cid from your models method.
Model
public function add() {
$data = array(
'name' => $_POST['companyName']
,'type' => $_POST['companyType']
,'active' => '1');
$this->db->insert('company', $data);
$cid = $this->db->insert_id();
$data2 = array(
'cid' => $cid
,'name' => $_POST['locationName']
,'address' => $_POST['locationAddress']);
$this->db->insert('locations', $data2);
// This returns your first inserts id
return $cid;
}
Controller
public function add() {
if (isset($_POST["add"]))
{
$id = $this->Company_model->add();
redirect('company/view/'.$id);
}
...

Related

Laravel Bulk Insert To Another Table From Selected Multiple Rows

I expected I can replicate multiple row from specific table to another table. But the problem, it cannot replicate password field data and spatie assignRole(). Whereas, all fields like email, name, username, etc are works properly.
public function approveMultiple(Request $request) {
$get_ids = $request->ids;
$ids = explode(',', $get_ids);
$users = \App\Applicant::whereIn('id', $ids);
$users->update(['status' => 'Approved']);
$find_selected = \App\Applicant::whereIn('id', $ids)->get();
$find_selected->makeHidden(['status', 'id']);
$find_selected->makeVisible(['password']);
$new_users = $find_selected->toArray();
$users = \App\User::insert($new_users);
//problem still lays here
//$users->assignRole('Applicant');
//$users->save();
return response()->json(['success' => "Selected User(s) successfully approved."]);
}
Trying to this approach but only insert one record
public function approveMultiple(Request $request) {
$get_ids = $request->ids;
$ids = explode(',', $get_ids);
//$users = \App\Applicant::whereIn('id', $ids);
//$users->update(['status' => 'Approved']);
//$find_selected = \App\Applicant::whereIn('id', $ids)->get();
$find_selected = \App\Applicant::whereIn('id', $ids)->firstOrFail();
$find_selected->makeHidden(['status', 'id']);
$find_selected->makeVisible(['password']);
$new_users = $find_selected->toArray();
//$users = \App\User::insert($new_users);
$users = \App\User::create([
'name' => $find_selected->name,
'username' => $find_selected->username,
'gender' => $find_selected->gender,
'email' => $find_selected->email,
'phone' => $find_selected->phone,
'password' => $find_selected->password,
'created_at' => $find_selected->created_at,
'updated_at' => $find_selected->updated_at,
]);
//problem lays here
$users->assignRole('Applicant');
$users->save();
return response()->json(['success' => "Selected User(s) successfully approved."]);
}
about password field , you need to make it visible with function like : makeVisible
for example:
$users->makeVisible('password')->toArray();
Edit 1:
about assignRole you must assign the role after you call the save() method
for example:
$users->password = $find_selected->password;
$users->save();
$users->assignRole('Applicant');
Edit 2:
public function approveMultiple(Request $request) {
$get_ids = $request->ids;
$ids = explode(',', $get_ids);
//$users = \App\Applicant::whereIn('id', $ids);
//$users->update(['status' => 'Approved']);
$find_selected = \App\Applicant::whereIn('id', $ids)->get();
//$find_selected = \App\Applicant::whereIn('id', $ids)->firstOrFail();
$find_selected->makeHidden(['status', 'id']);
$find_selected->makeVisible(['password']);
$new_users = $find_selected->toArray();
//$users = \App\User::insert($new_users);
foreach($find_selected as $new_users){
$user = \App\User::create($new_users);
$user->assignRole('Applicant');
}
return response()->json(['success' => "Selected User(s) successfully approved."]);
}
i think the problem lays in this line:
$users = \App\User::insert($new_users);
insert method returns a boolean that indicate the insertion operation has succeeded or not ...
so you $users variable will hold a boolean value ...
and
$users->assignRole('Applicant');
$users->password = $find_selected->password;
wont work
you could use :
$find_selected->makeVisible(['password']);
foreach($find_selected as $user)
{
$newUser= new User();
$newUser->password = $user->password;
$newUser->save();
$newUser->assignRole('Applicant');
}

Laravel isDirty method mass assignment

My code is saving data of only one field(efirst) if it's changed by the isDirty() method, and it's working correctly. How can I achieve the same result if I have ten fields without writing each field name?
Controller:
public function update(TeacherRequest $request, $id)
{
$teacher = Teacher::find($id);
$teacher->efirst = $request->efirst;
if ($teacher->isDirty()) {
$new_data = $teacher->efirst;
$old_data = $teacher->getOriginal('efirst');
if ($teacher->save()) {
$teacher->update($request->except('qual_id', 'id', 'profile_pic'));
DB::table('teacher_logs')->insert(
[
'user_id' => $user->id,
'teacher_id' => $teacher->id,
'old_value' => $old_data,
'new_value' => $new_data,
]);
}
}
}
If you don't want to write $teacher->field = $request->value; a bunch of times, you may use a loop:
foreach($request->except("_token") AS $field => $value){
$teacher->{$field} = $value;
}
if($teacher->isDirty()){
$new_data = [];
$old_data = [];
foreach($request->except("_token") AS $field => $value){
$new_data[$field] = $value;
$old_data[$field] = $teacher->getOriginal($field);
}
}
Note: You'll need to convert $new_data and $old_data to arrays so you can reference each field and value properly, and do some additional logic on the insert of your teacher_logs table to handle, but that should give you an idea.

How to insert value of my checkbox to different column in database codeigniter

This should be like this
ID|access1|access2|access3|
and values:
1|1|0|1
//myController
$basic_data = array();
$select_access1 = $_POST("select_access1");
$select_access2 = $_POST("select_access2");
$select_access3 = $_POST("select_access3");
$select_access4 = $_POST("select_access4");
$select_access5 = $_POST("select_access5");
$basic_data[] = array('accs_trans_sec'=>$select_access1,'accs_acctng_sec'=>$select_access2, 'accs_admin_sec'=>$select_access3,'accs_dashboard_sec'=> $select_access4, 'accs_reports_sec'=>$select_access5);
$this->RoleModel->saveRole($basic_data);
//myModel
public function saveRole($basic_data)
{
foreach($basic_data as $value) {
$this->db->insert('roles_global_access', $basic_data);
}}
You can set that data to array just like this:
$data = array(
'column1' => 'My Value 1',
'column2' => 'My Value 2',
'column3' => 'My Value 3'
);
$this->db->insert("table_name", $data);
Let's assume that you are getting the values of your checkbox based on your $_POST variables.
Since you've declared $basic_data as array() no need to cast it as $basic_data[].
So on your controller it should be like this:
$basic_data = array(
'accs_trans_sec'=>$select_access1,
'accs_acctng_sec'=>$select_access2,
'accs_admin_sec'=>$select_access3,
'accs_dashboard_sec'=> $select_access4,
'accs_reports_sec'=>$select_access5
);
And your model there's no need to use loop since you are inserting Object data it should look like this:
public function saveRole($basic_data)
{
$this->db->insert('roles_global_access', $basic_data);
return ($this->db->affected_rows() != 1) ? false : true;
}
so basically, if the model returns true then it successfully inserted the data.
To check if data is inserted successfully:
$result = $this->RoleModel->saveRole($basic_data);
if($result == true){
echo ("Successfully inserted!");
}else{
echo ("Problem!");
}
First, you are not getting post data in the correct way. With $_POST have to use square brackets [].
Second, Don't use foreach loop in the model
Get data in the controller like this
$basic_data = array(
'accs_trans_sec' => $_POST['select_access1'],
'accs_acctng_sec' => $_POST['select_access2'],
'accs_admin_sec' => $_POST['select_access3'],
'accs_dashboard_sec' => $_POST['select_access4'],
'accs_reports_sec' => $_POST['select_access5']
);
$this->RoleModel->saveRole($basic_data);
Model
public function saveRole($basic_data){
return $this->db->insert('roles_global_access', $basic_data);
}
You should try this.
Controller:
$this->RoleModel->saveRole($_POST);
Model:
public function saveRole($basic_data){
extract($basic_data);
$dataset = array(
'accs_trans_sec' => $basic_data['select_access1'],
'accs_acctng_sec' => $basic_data['select_access2'],
'accs_admin_sec' => $basic_data['select_access3'],
'accs_dashboard_sec' => $basic_data['select_access4'],
'accs_reports_sec' => $basic_data['select_access5']
);
$this->db->insert('roles_global_access', $dataset);
}

codeigniter how to store real time data

public function insert_employee($fldCompanyStringID) {
$fldCompanyID = getCoompanyByStringID($fldCompanyStringID)->fldCompanyID;
$data = array(
'fldUserFName' => $this->input->post('fldUserFName'),
'fldUserBankAccountNumber' => $this->input->post('fldUserBankAccountNumber')
);
$data2 = array(
'fldWorkHistoryCompanyName' => $this->input->post('fldWorkHistoryCompanyName')
);
if ($this->db->insert('tblUser', $data)&& $this->db->insert(' tblWorkHistory', $data2)) {
$this->session->set_flashdata('success_msg', 'New Employee is inserted');
}
}
The tblUser table auto generates a userID. I want to take that userID and store it into the tblWorkHistory table **
Here CodeIgniter transactions will help you.
https://www.codeigniter.com/user_guide/database/transactions.html
Please use this code --
<?php
public function insert_employee($fldCompanyStringID) {
$this->db->trans_start();
$fldCompanyID = getCoompanyByStringID($fldCompanyStringID)->fldCompanyID;
/* Insert User */
$data = array(
'fldUserFName' => $this->input->post('fldUserFName'),
'fldUserBankAccountNumber' => $this->input->post('fldUserBankAccountNumber')
);
$this->db->insert('tblUser', $data)
$insert_id = $this->db->insert_id();
/* Insert Work History */
$data2 = array(
'userID' => $insert_id,
'fldWorkHistoryCompanyName' => $this->input->post('fldWorkHistoryCompanyName')
);
$this->db->insert('tblWorkHistory', $data2)
/* Manage Transaction */
$this->db->trans_complete();
if ($this->db->trans_status() === FALSE){
$this->session->set_flashdata('error_msg', 'Failed, please try again');
}else{
$this->session->set_flashdata('success_msg', 'New Employee is inserted');
}
}
?>
$this->db->insert_id() is used to get the last insert auto increment id data.
$this->db->insert('tblUser', $data);
$insert_id = $this->db->insert_id();
if($insert_id) {
$data2 = array(
'userID' => $insert_id,
'fldWorkHistoryCompanyName' => $this->input->post('fldWorkHistoryCompanyName')
);
if ($this->db->insert(' tblWorkHistory', $data2)) {
$this->session->set_flashdata('success_msg', 'New Employee is inserted');
}
} else {
$this->session->set_flashdata('error_msg', 'Something went wrong');
}

Difference between Redirect::to() and View::make()

I have a blade form that posts to Controller, the controller then will redirect to the same URL after performing some operations.
Before redirecting to the user, two variables will be passed. My problem is that when using Redirect::to() only the ->with('item_list',$item_list) is made available for the view, while ->with('added_items',$added_items) when using the $added_items variable in the view gives me the error:
ErrorException
Undefined variable: added_items (View: /var/www/mw/app/views/delivery->
requests/create.blade.php)
Controller
if (Input::has('addItem'))
{
if (Session::has('added-items'))
{
$id = Input::get('item_id');
$new_item = Item::find($id);
Session::push('added-items', [
'item_id' => $id,
'item_name' => $new_item->item_name,
'item_quantity' => Input::get('item_quantity')
]);
$array = Session::get('added-items');
//move outside foreach loop because we don't want to reset it
$total = array();
foreach ($array as $key => $value)
{
$id = $value['item_id'];
$quantity = $value['item_quantity'];
if (!isset($total[$id]))
{
$total[$id] = 0;
}
$total[$id] += $quantity;
}
$items = array();
foreach($total as $item_id => $item_quantity)
{
$new_item = Item::find($item_id);
$items[] = array(
'item_id' => $item_id,
'item_name' => $new_item->item_name,
'item_quantity' => $item_quantity
);
}
Session::put('added-items', $items);
}
else
{
$id = Input::get('item_id');
$new_item = Item::find($id);
Session::put('added-items', [
0 => [
'item_id' => $id,
'item_name' => $new_item->item_name,
'item_quantity' => Input::get('item_quantity')
]
]);
}
// pass the items again to the page
$item_list = Item::lists('item_name', 'id');
$added_items = Session::get('added-items');
return View::make('delivery-requests/create')
->with('added_items',$added_items)
->with('item_list', $item_list);
}
The reason I used Redirect::to() is that it maintains the same URL which is /delivery-requests/create
But when I use View::make() I can access the $added_items variable just fine, but the URL now becomes /delivery-requests , even if I explicitly put it like this:
return View::make('delivery-requests/create')
->with('added_items',$added_items)
->with('item_list', $item_list);
My question is why can't Redirect::to() read the $added_items variable on the view
Instead of redirecting to the route, return the method which is at the end of that route with any additional variables you need.
return $this->create()->with('added_items', $added_items)->with('item_list', $item_list) where create() is the method which is being used on the route delivery-requests/create.
Redirect is probably what you are actually after then,
Redirect::to()->with('item_list', $item_list);

Resources