This method does only save but i want it will do insert, update and delete in codeigniter
//Gallery Category CRUD Module
public function galleryCategory(){
if (!empty($_POST['gallery_cat_name'])){
$data = $this->input->post();
$data['gallery_cat_date'] = date("Y-m-d", strtotime(str_replace('/', '-', $this->input->post('gallery_cat_date'))));
//Data save
$response = $this->MyModel->save('gallery_category', $data);
if ($response) {
$sdata['success_alert'] = "Saved successfully";
}else{
$sdata['failure_alert'] = "Not Saved successfully";
}
$this->session->set_userdata($sdata);
redirect('back/galleryCategoryCreate');
}else{
$sdata['failure_alert'] = "Try again";
$this->session->set_userdata($sdata);
redirect('back/galleryCategoryCreate');
}
}
You don't need to create Model with your queries for basic crud operations.
CodeIgniter provides those as Query Builder class.
From CodeIgniter Documentation
Selecting Data
The following functions allow you to build SQL SELECT statements.
$this->db->get()
Runs the selection query and returns the result. Can be used by itself to retrieve all records from a table:
$query = $this->db->get('mytable'); // Produces: SELECT * FROM mytable
Inserting Data
$this->db->insert()
Generates an insert string based on the data you supply, and runs the query. You can either pass an array or an object to the function. Here is an example using an array:
$data = array(
'title' => 'My title',
'name' => 'My Name',
'date' => 'My date'
);
$this->db->insert('mytable', $data);
// Produces: INSERT INTO mytable (title, name, date) VALUES ('My title', 'My name', 'My date')
Updating Data
$this->db->update()
Generates an update string and runs the query based on the data you supply. You can pass an array or an object to the function. Here is an example using an array:
$data = array(
'title' => $title,
'name' => $name,
'date' => $date
);
$this->db->where('id', $id);
$this->db->update('mytable', $data);
// Produces:
//
// UPDATE mytable
// SET title = '{$title}', name = '{$name}', date = '{$date}'
// WHERE id = $id
Deleting Data
$this->db->delete()
Generates a delete SQL string and runs the query.
$this->db->delete('mytable', array('id' => $id)); // Produces: // DELETE FROM mytable // WHERE id = $id
The first parameter is the table name, the second is the where clause. You can also use the where() or or_where() functions instead of passing the data to the second parameter of the function:
$this->db->where('id', $id);
$this->db->delete('mytable');
// Produces:
// DELETE FROM mytable
// WHERE id = $id
You must refer the documentation once, there are a lot of helpers.
<?php
class Crud_Model extends CI_Model{
public function get_where($table,$where){
return $data = $this->db->where($where)->get($table)->result_array();
}
public function select($table){
return $data = $this->db->get($table)->result_array();
}
public function insert($table,$data){
return $query = $this->db->insert($table,$data);
}
function delete($table,$where){
return $del = $this->db->where($where)->delete($table);
}
public function edit($table,$where){
return $data = $this->db->where($where)->get($table)->result_array();
}
public function update($table,$data,$where){
return $query = $this->db->where($where)->update($table,$data);
}
}
?>
I want to make update function with 2 where clauses, this is my model code :
function updateJawabanSensus($where,$where1,$data) {
$this->db->where('id_jawaban',$where);
$this->db->where('id_sensus',$where1);
$this->db->update($this->_table, $data);
return $this->db->affected_rows();
}
controller code :
function update_jawaban_sensus() {
$id_jawaban = $this->input->post('id_jawaban', TRUE);
$id_sensus = $this->input->post('id_sensus', TRUE);
$id_keluarga = $this->input->post('id_keluarga', TRUE);
$id_pertanyaan_sensus = $this->input->post('id_pertanyaan_sensus', TRUE);
$jawaban = $this->input->post('jawab_0', TRUE);
$id_indikator = $this->input->post('idInd_0', TRUE);
$indikator = $this->input->post('indikator_0');
$bobot = $this->m_pilihan_jawaban->get_bobot($id_sensus,$jawaban);
$nilai_bobot = $bobot * $indikator;
$data = array(
'id_jawaban' => $id_jawaban,
'id_sensus' => $id_sensus,
'id_indikator' => $id_indikator,
'id_keluarga' => $id_keluarga,
'id_pertanyaan_sensus' => $id_pertanyaan_sensus,
'jawaban' => $jawaban,
'nilai_bobot' => $nilai_bobot
);
//echo json_encode($jawaban);
$result = $this->m_jawaban_sensus->updateJawabanSensus(array('id_jawaban' => $id_jawaban,'id_sensus' => $id_sensus), $data);
redirect('indikatorkesejahteraan/c_jawaban_sensus/konfirmasi/'.$id_sensus.'/'.$id_keluarga);
}
but when i click the update button the data can't change..thanks for your attention
First problem: you are not showing where $this->_table is defined in your model. (I will assume you are setting this in your __construct)
Second problem: your model method expects three parameters: updateJawabanSensus($where,$where1,$data), but you are only sending two:
updateJawabanSensus(array('id_jawaban' => $id_jawaban,'id_sensus' => $id_sensus), $data);
Solution
Codeigniter will accept multiple where clauses in an array. Since you already have an array, just send it once, and permit your model method to accept only two parameters.
Controller:
$arr = array(
'id_jawaban' => $id_jawaban,
'id_sensus' => $id_sensus
);
$this->m_jawaban_sensus->updateJawabanSensus($arr, $data);
Model:
function updateJawabanSensus($where,$data) {
$this->db->where($where);
$this->db->update($this->_table, $data);
return $this->db->affected_rows();
}
Source: http://www.codeigniter.com/user_guide/database/query_builder.html#looking-for-specific-data
You are sending only parameter form you controller.
$result = $this->m_jawaban_sensus->updateJawabanSensus(array('id_jawaban' => $id_jawaban,'id_sensus' => $id_sensus), $data);
Instead you using two where condition you can simply do in once.
Model
function updateJawabanSensus($where,$data) {
$this->db->where($where);
$this->db->update($this->_table, $data);
return $this->db->affected_rows();
}
I want to make a relation table in table pelatih and table absen. But when I try to make a relation id_pelatih it always input number "3".
This is the controller:
function absen()
{
$this->load->library('user_agent');
$nim = $this->uri->segment(4);
$id_user = $this->session->userdata('user_id');
$id_pelatih = $id_pelatih;
$this->load->model('mabsensi');
$data = array(
'id_pelatih' => $this->mlogin->get_data_pelatih_by_id_user($id_user)->id_pelatih,
'nim' => $nim,
'tanggal' => date('Y-m-d H:i:s'),
'keterangan' => 'Hadir'
);
$this->mabsensi->insert_absensi($data);
redirect($this->agent->referrer());
}
This is the model
function get_data_pelatih_by_id_user($id_user)
{
$this->db->select('*')
->from('pelatih as a, user as u')
->where('a.id_user = u.id_user')
->limit(1);
return $this->db->get()->row();
}
Please tell me how to solved this.
Your model isn't correct. If you want to get data from different tables you should use JOIN. And you have to say which record you need. So, add a WHERE statement to your query.
function get_data_pelatih_by_id_user($id_user)
{
$this->db->SELECT('*')
->FROM('user')
->WHERE('id_user', $id_user) // your parameter, you did not use it
->JOIN('pelatih', 'pelatih.id_user = user.id_user');
return $this->db->get();
}
Also have a look at the documentation: http://ellislab.com/codeigniter/user-guide/database/active_record.html
I'm currently using the below code to insert data in a table:
<?php
public function saveDetailsCompany()
{
$post = Input::All();
$data = new Company;
$data->nombre = $post['name'];
$data->direccion = $post['address'];
$data->telefono = $post['phone'];
$data->email = $post['email'];
$data->giro = $post['type'];
$data->fecha_registro = date("Y-m-d H:i:s");
$data->fecha_modificacion = date("Y-m-d H:i:s");
if ($data->save()) {
return Response::json(array('success' => true), 200);
}
}
I want to return the last ID inserted but I don't know how to get it.
Kind regards!
After save, $data->id should be the last id inserted.
$data->save();
$data->id;
Can be used like this.
return Response::json(array('success' => true, 'last_insert_id' => $data->id), 200);
For updated laravel version try this
return response()->json(array('success' => true, 'last_insert_id' => $data->id), 200);
xdazz is right in this case, but for the benefit of future visitors who might be using DB::statement or DB::insert, there is another way:
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
]);
Refer: https://laravel.com/docs/5.1/queries#inserts
For anyone who also likes how Jeffrey Way uses Model::create() in his Laracasts 5 tutorials, where he just sends the Request straight into the database without explicitly setting each field in the controller, and using the model's $fillable for mass assignment (very important, for anyone new and using this way): I read a lot of people using insertGetId() but unfortunately this does not respect the $fillable whitelist so you'll get errors with it trying to insert _token and anything that isn't a field in the database, end up setting things you want to filter, etc. That bummed me out, because I want to use mass assignment and overall write less code when possible. Fortunately Eloquent's create method just wraps the save method (what #xdazz cited above), so you can still pull the last created ID...
public function store() {
$input = Request::all();
$id = Company::create($input)->id;
return redirect('company/'.$id);
}
**** For Laravel ****
Firstly create an object, Then set attributes value for that object, Then save the object record, and then get the last inserted id. such as
$user = new User();
$user->name = 'John';
$user->save();
// Now Getting The Last inserted id
$insertedId = $user->id;
echo $insertedId ;
There are several ways to get the last inserted id. All are based on what method do you used when inserting. In your case you can get last Id like the following:
$data->save();
$data->id;
For others who need to know how can they get last inserted id if they use other insert methods here is how:
Using create() method
$book = Book::create(['name'=>'Laravel Warrior']);
$lastId = $book->id;
Using insertGetId()
$id = DB::table('books')->insertGetId( ['name' => 'Laravel warrior'] ); $lastId = $id;
Using lastInsertId() method
$lastId = DB::getPdo()->lastInsertId();
Reference https://easycodesolution.com/2020/08/22/last-inserted-id-in-laravel/
In laravel 5: you can do this:
use App\Http\Requests\UserStoreRequest;
class UserController extends Controller {
private $user;
public function __construct( User $user )
{
$this->user = $user;
}
public function store( UserStoreRequest $request )
{
$user= $this->user->create([
'name' => $request['name'],
'email' => $request['email'],
'password' => Hash::make($request['password'])
]);
$lastInsertedId= $user->id;
}
}
This worked for me in laravel 4.2
$id = User::insertGetId([
'username' => Input::get('username'),
'password' => Hash::make('password'),
'active' => 0
]);
Here's an example:
public static function saveTutorial(){
$data = Input::all();
$Tut = new Tutorial;
$Tut->title = $data['title'];
$Tut->tutorial = $data['tutorial'];
$Tut->save();
$LastInsertId = $Tut->id;
return Response::json(array('success' => true,'last_id'=>$LastInsertId), 200);
}
Use insertGetId to insert and get inserted id at the same time
From doc
If the table has an auto-incrementing id, use the insertGetId method
to insert a record and then retrieve the ID:
By Model
$id = Model::insertGetId(["name"=>"Niklesh","email"=>"myemail#gmail.com"]);
By DB
$id = DB::table('users')->insertGetId(["name"=>"Niklesh","email"=>"myemail#gmail.com"]);
For more details : https://laravel.com/docs/5.5/queries#inserts
For insert()
Example:
$data1 = array(
'company_id' => $company_id,
'branch_id' => $branch_id
);
$insert_id = CreditVoucher::insert($data1);
$id = DB::getPdo()->lastInsertId();
dd($id);
Here is how we can get last inserted id in Laravel 4
public function store()
{
$input = Input::all();
$validation = Validator::make($input, user::$rules);
if ($validation->passes())
{
$user= $this->user->create(array(
'name' => Input::get('name'),
'email' => Input::get('email'),
'password' => Hash::make(Input::get('password')),
));
$lastInsertedId= $user->id; //get last inserted record's user id value
$userId= array('user_id'=>$lastInsertedId); //put this value equal to datatable column name where it will be saved
$user->update($userId); //update newly created record by storing the value of last inserted id
return Redirect::route('users.index');
}
return Redirect::route('users.create')->withInput()->withErrors($validation)->with('message', 'There were validation errors.');
}
Although this question is a bit dated. My quick and dirty solution would look like this:
$last_entry = Model::latest()->first();
But I guess it's vulnerable to race conditions on highly frequented databases.
After saving model, the initialized instance has the id:
$report = new Report();
$report->user_id = $request->user_id;
$report->patient_id = $request->patient_id;
$report->diseases_id = $request->modality;
$isReportCreated = $report->save();
return $report->id; // this will return the saved report id
You can easily fetch last inserted record Id
$user = User::create($userData);
$lastId = $user->value('id');
It's an awesome trick to fetch Id from the last inserted record in the DB.
After
$data->save()
$data->id will give you the inserted id,
Note: If your autoincrement column name is sno then you should use
$data->sno and not $data->id
After saving a record in database, you can access id by $data->id
return Response::json(['success' => true, 'last_insert_id' => $data->id], 200)
In Laravel 5.2 i would make it as clean as possible:
public function saveContact(Request $request, Contact $contact)
{
$create = $contact->create($request->all());
return response()->json($create->id, 201);
}
For Laravel, If you insert a new record and call $data->save() this function executes an INSERT query and returns the primary key value (i.e. id by default).
You can use following code:
if($data->save()) {
return Response::json(array('status' => 1, 'primary_id'=>$data->id), 200);
}
You can do this:
$result=app('db')->insert("INSERT INTO table...");
$lastInsertId=app('db')->getPdo()->lastInsertId();
$objPost = new Post;
$objPost->title = 'Title';
$objPost->description = 'Description';
$objPost->save();
$recId = $objPost->id; // If Id in table column name if other then id then user the other column name
return Response::json(['success' => true,'id' => $recId], 200);
For get last inserted id in database
You can use
$data = new YourModelName;
$data->name = 'Some Value';
$data->email = 'abc#mail.com';
$data->save();
$lastInsertedId = $data->id;
here $lastInsertedId will gives you last inserted auto increment id.
The shortest way is probably a call of the refresh() on the model:
public function create(array $data): MyModel
{
$myModel = new MyModel($dataArray);
$myModel->saveOrFail();
return $myModel->refresh();
}
You can also try like this:
public function storeAndLastInrestedId() {
$data = new ModelName();
$data->title = $request->title;
$data->save();
$last_insert_id = $data->id;
return $last_insert_id;
}
Here it is how it worked for me, family_id is the primary key with auto increment I am using Laravel7
public function store(Request $request){
$family = new Family();
$family->family_name = $request->get('FamilyName');
$family->family_no = $request->get('FamilyNo');
$family->save();
//family_id is the primary key and auto increment
return redirect('/family/detail/' . $family->family_id);
}
Also in the Model Family file which extends Model, should have the increment set to true otherwise the above $family-->family_id will return empty
public $incrementing = true;
Using Eloquent Model
$user = new Report();
$user->email= 'johndoe#example.com';
$user->save();
$lastId = $user->id;
Using Query Builder
$lastId = DB::table('reports')->insertGetId(['email' => 'johndoe#example.com']);
After Saving $data->save(). all data is pushed inside $data. As this is an object and the current row is just saved recently inside $data. so last insertId will be found inside $data->id.
Response code will be:
return Response::json(array('success' => true, 'last_insert_id' => $data->id), 200);
You can get last inserted id with same object you call save method;
$data->save();
$inserted_id = $data->id;
So you can simply write:
if ($data->save()) {
return Response::json(array('success' => true,'inserted_id'=>$data->id), 200);
}
public function store( UserStoreRequest $request ) {
$input = $request->all();
$user = User::create($input);
$userId=$user->id
}
Using Eloquent Model
use App\Company;
public function saveDetailsCompany(Request $request)
{
$createcompany=Company::create(['nombre'=>$request->input('name'),'direccion'=>$request->input('address'),'telefono'=>$request->input('phone'),'email'=>$request->input('emaile'),'giro'=>$request->input('type')]);
// Last Inserted Row ID
echo $createcompany->id;
}
Using Query Builder
$createcompany=DB::table('company')->create(['nombre'=>$request->input('name'),'direccion'=>$request->input('address'),'telefono'=>$request->input('phone'),'email'=>$request->input('emaile'),'giro'=>$request->input('type')]);
echo $createcompany->id;
For more methods to get Last Inserted Row id in Laravel : http://phpnotebook.com/95-laravel/127-3-methods-to-get-last-inserted-row-id-in-laravel