I'm trying to do simple function edit student table field, But its updating only first field: first_name
My controller.
public function editStudent(Request $request)
{
$studId = $request->get('studId');
$studFirstName = $request->get('firstName');
$studLastName = $request->get('lastName');
$studGender = $request->get('gender');
$studBirthday = $request->get('birthday');
$studSchoolId = $request->get('schoolId');
$update = Student::where('id', $studId)->update(['first_name' => $studFirstName],
['last_name' => $studLastName], ['gender' => $studGender], ['birthday', $studBirthday], ['school_id' => $studSchoolId]);
return response()->json([
"update" => $update,
]);
}
Update takes a single array, you're passing in multiple arrays
$update = Student::where('id', $studId)
->update([
'first_name' => $studFirstName,
'last_name' => $studLastName,
'gender' => $studGender,
'birthday'=> $studBirthday,
'school_id' => $studSchoolId
]);
Its better to get the item from DB then update that on a second query:
$student = Student::find($studId);
$student->update([
'first_name' => $request->firstName,
'last_name' => $request->lastName,
'gender' => $request->gender,
'birthday'=> $request->birthday,
'school_id' => $request->schoolId
]);
Related
I’m getting this error: Indirect modification of overloaded element of App\Models\ has no effect, change ->get(); to ->first->toArray(); another error Call to a member function toArray() on null
here the code
$penjualan = Penjualan::find(session('id_penjualan'));
$detail = PenjualanDetail::with('produk')->where('id_penjualan', session('id_penjualan'))->get();
$transaction = new Penjualan();
foreach ($detail as $item) {
$transaction_details = [
'order_id' => $penjualan->id_penjualan,
'gross_amount' => $penjualan->bayar,
];
$item_details = [
'id' => $penjualan->id_penjualan,
'price' => $item->harga_jual,
'quantity' => $item->jumlah,
'name' => $item->produk->nama_produk,
];
$customer_details = [
'first_name' => $request->get('uname'),
'last_name' => '',
'email' => $request->get('email'),
'phone' => $request->get('number'),
];
$transaction = [
'transaction_details' => $transaction_details,
'item_details' => $item_details,
'customer_details' => $customer_details,
];
}
$snapToken = Midtrans\Snap::getSnapToken($transaction);
$transaction->snap_token = $snapToken;
$transaction->save();
anyone could help me to fix this?
I have done Midtrans payment before.
The problem you've got with your current code are
you want to store snap_token inside your Penjualan model, but you use new Penjualan()
when multiple items are ordered, your code do not support it cause $item_details is a single array inside foreach loop
So here is an updated code with some notes and recommendations.
$id = session('id_penjualan');
$validated = $request->validate([
'uname' => 'required|string',
// 'lname' => 'nullable|string',
'email' => 'required|string',
'number' => 'required|string',
]);
// use single query to retrieve Penjualan and PenjualanDetail
// for product name, recommend to store it within PenjualanDetail, along with price and base_price
$penjualan = Penjualan::query()
->with('details')
->find($id);
if (!$penjualan) {
// you can redirect your customer to cart or any other page
return redirect('cart')->with('error', 'Can not find Penjualan.');
}
$item_details = [];
foreach ($penjualan->details as $item) {
$item_details[] = [
'id' => $item->id,
'price' => $item->harga_jual,
'quantity' => $item->jumlah,
// recommended product's name to be stored within PenjualanDetail
'name' => $item->nama_produk,
];
}
$transaction_details = [
'order_id' => $penjualan->id_penjualan,
// "bayar" must not contain any decimal, use cast Money
'gross_amount' => $penjualan->bayar,
];
// Optional
$customer_details = [
'first_name' => $validated['uname'],
'last_name' => '', // $validated['lname'],
'email' => $validated['email'],
'phone' => $validated['number'],
// 'billing_address' => '',
// 'shipping_address' => '',
];
// this is a simple array that will be sent to method getSnapToken()
$transaction = [
'transaction_details' => $transaction_details,
'customer_details' => $customer_details,
'item_details' => $item_details,
];
// this method only accept good old array
$snapToken = Midtrans\Snap::getSnapToken($transaction);
$penjualan->snap_token = $snapToken;
// recommend to store your customer detail here, either multiple fields or single array field storing $customer_details
// $penjualan->first_name = $customer_details['first_name'];
// $penjualan->last_name = $customer_details['last_name'];
// $penjualan->email = $customer_details['email'];
// $penjualan->phone = $customer_details['phone'];
// $penjualan->billing_address = $customer_details['billing_address'];
// $penjualan->shipping_address = $customer_details['shipping_address'];
$penjualan->save();
I commented out some parts that you might not use, where I did used them in the past.
Feel free to adjust them to suite your needs.
public function getSnapToken ()
{
$id = session('id_penjualan');
$member = Member::orderBy('nama')->get();
$penjualan = Penjualan::with(['penjualan_detail' => $detail = function ($query) {
$query->where('item', 'kode_produk, subtotal, jumlah, nama_produk');
}])->where('id_penjualan', ('id_penjualan'))
->orderBy('id_penjualan')
->get();
$transaction = array($penjualan);
foreach ( $detail as $item ) {
$transaction_details = [
'order_id' => $this->penjualan->id_penjualan,
'gross_amount' => $this->penjualan->bayar,
];
$item_details = [
'id' => $item->produk->kode_produk,
'price' => $item->jumlah * $item->subtotal,
'quantity' => $item->jumlah,
'name' => $item->produk->nama_produk,
];
$customer_details = [
'id' => $penjualan->member->kode_member,
'first_name' => $validated['uname'],
'last_name' => $validated['lname'],
'email' => $validated['email'],
'phone' => $validated['number'],
// 'billing_address' => '',
// 'shipping_address' => '',
];
$transaction = [
'transaction_details' => $transaction_details,
'item_details' => $item_details,
'customer_details' => $customer_details,
];
}
$snap_token = '';
try {
$snap_token = \Midtrans\Snap::getSnapToken($transaction);
}
catch (\Exception $e) {
echo $e->getMessage();
}
echo "snap_token = ".$snap_token;
}
public function payment(Penjualan $penjualan)
{
$snap_token = $penjualan->snap_token;
if (is_null($snap_token)) {
$midtrans = new CreateSnapTokenService($penjualan);
$snap_token = $midtrans->getSnapToken();
$snap_token = Penjualan::where('id_penjualan')->update(['snap_token' => $snap_token]);
}
return view('penjualan.payment', ['snap_token'=>$snap_token]);
}
So i'm trying to learn using codeigniter 3, and i'm trying to get the id from users table, the name of the id column on users table is user_id, and i have another table called lowongan, it has id_user to get the id(user_id) from the users table. So when i tried to input and submit that input to be saved into the database, the id_user is null, but i already set it like this
$id_user = $this->session->userdata('user_id');
$data = array(
'id_user' => $id_user
);
But it's still null how can i fix this??
The model :
<?php
class M_lowongan extends CI_Model{
public function show_lowongan(){
return $this->db->get('lowongan');
}
public function input_data($data, $table){
$this->db->insert($table, $data);
}
}
The Controller :
public function store_lowongan(){
$id_user = $this->session->userdata('user_id');
$title = $this->input->post('title');
$lokasi = $this->input->post('lokasi');
$level_pekerja = $this->input->post('level_pekerja');
$pengalaman_kerja = $this->input->post('pengalaman_kerja');
$pendidikan = $this->input->post('pendidikan');
$alamat = $this->input->post('alamat');
$no_wa = $this->input->post('no_wa');
$no_telp = $this->input->post('no_telp');
$min_gaji = $this->input->post('min_gaji');
$max_gaji = $this->input->post('max_gaji');
$job_desc = $this->input->post('job_desc');
$data = array(
'id_user' => $id_user,
'title' => $title,
'lokasi' => $lokasi,
'level_pekerja' => $level_pekerja,
'pengalaman_kerja' => $pengalaman_kerja,
'pendidikan' => $pendidikan,
'alamat' => $alamat,
'no_wa' => $no_wa,
'no_telp' => $no_telp,
'min_gaji' => $min_gaji,
'max_gaji' => $max_gaji,
'job_desc' => $job_desc
);
$this->m_lowongan->input_data($data, 'lowongan');
redirect ('dashboard');
}
do you already create the session? If not, you can create like this:
$row = $this->Auth_model->get_by_username($this->input->post('username'));
$session = array(
'id_users' => $row->id_users,
'name' => $row->name,
'username' => $row->username,
'email' => $row->email,
'usertype' => $row->usertype,
'photo' => $row->photo,
'photo_thumb' => $row->photo_thumb,
);
$this->session->set_userdata($session);
After that you can easily call the session like:
$this->session->name
My UPDATE function is as follows; I manually set some fields in the users table. In other words, it is necessary to update only the name part from the incoming request. If the lawyer has been removed from the edit form, it must also be removed from the users table. If the lawyer name has been updated, it should also be updated in the table.
How can I complete the update process.
public function update(Request $request, LegalPursuit $legalPursuit, $id)
{
$request->validate([
'BRANCH_ID' => 'required',
'MAIN_ACCOUNT_ID' => 'required',
'DEPOSITOR_ID' => 'required',
'ACCOUNT_HOLDER' => 'required|max:255',
'CURRENT_SCREEN_BALANCE' => 'required',
'TRL_EQUIVALENT' => 'required'
]);
//dd($request->all());
if($request->input('PROVISION') == 'on'){
$request->request->add(['PROVISION' => 'yes']);
}
$request->FOLLOW_UP_DATE = \Carbon\Carbon::parse($request->input('FOLLOW_UP_DATE'))->format('Y-m-d');
$request->DATE_OF_ATTORNEY_SUBMISSION = \Carbon\Carbon::parse($request->input('DATE_OF_ATTORNEY_SUBMISSION'))->format('Y-m-d');
$request->PROVISION_DATE = \Carbon\Carbon::parse($request->input('PROVISION_DATE'))->format('Y-m-d');
$request->request->add(['FOLLOW_UP_DATE' => $request->FOLLOW_UP_DATE]); //dd request
$request->request->add(['DATE_OF_ATTORNEY_SUBMISSION' => $request->DATE_OF_ATTORNEY_SUBMISSION]); //dd request
$request->request->add(['PROVISION_DATE' => $request->PROVISION_DATE]); //dd request
if(is_array($request->input('LAWYERS')) AND !empty($request->input('LAWYERS'))){
$lawyerArray = $request->input('LAWYERS');
//dd($lawyer_array);
$lawyerArray->each(function($lawyer) use ($user) {
$user->lawyerArray()->updateOrCreate(
[
'legalpursuit_id' => $id],
[
'role_id' => 1,
'name' => $request->input('LAWYERS'),
'email' => 'aa#'.rand().'.com',
'email_verified_at' => now(),
'password'=> Hash::make('1q2w3e4r'),
'department' => 'Avukat',
'gender' => 'Kadın',
'marital_status' => 'Bekar',
'job' => 'Avukat',
'phone' => '+9055555',
'internal_no' => '0',
'active' => '0',
'deleted' => '0'
]
);
}
);
for($x = 0; $x < count($request->input('LAWYERS')); $x++){
User::updateOrInsert(
['legalpursuit_id' => $id],
[
'role_id' => 1,
'name' => $request->input('LAWYERS'),
'email' => 'aa#'.rand().'.com',
'email_verified_at' => now(),
'password'=> Hash::make('1q2w3e4r'),
'department' => 'Avukat',
'gender' => 'Kadın',
'marital_status' => 'Bekar',
'job' => 'Avukat',
'phone' => '+9055555',
'internal_no' => '0',
'active' => '0',
'deleted' => '0'
]);
}
/*foreach($lawyer_array as $lawyer) {
$updateLaywer =
}
dd($updateLaywer);
/*
$getUsers = DB::table('users')
->select(['users.id'])
->leftJoin('legalpursuit', 'users.legalpursuit_id', '=', 'legalpursuit.ID')
->where('legalpursuit.ID', '=', $id)
->get();
$lawyersChanged = DB::table('users')
->whereIn('id', $getUsers)
->update(
[
'name' => ''
]
);
*/
//echo "asdfasdfasdf";exit;
/*
$lawyersChanged = User::updateOrCreate(
['legalpursuit_id' => $id],
['name' => $request->input('LAWYERS')]
);
//echo $lawyersChanged; exit;*/
}else{
$getUsers = DB::table('users')
->select(['users.id'])
->leftJoin('legalpursuit', 'users.legalpursuit_id', '=', 'legalpursuit.ID')
->where('legalpursuit.ID', '=', $id)
->get();
$getUsers->delete();
//echo "aaaaaaaa";exit;
}
if(is_array($request->input('GUARANTORS')) AND !empty($request->input('GUARANTORS'))){
echo "asdfasdfadsf";exit;
$guarantorsChanged = Guarantors::updateOrCreate(
['legalpursuit_id' => $id],
['name' => $request->input('GUARANTORS')]
);
}else{
//echo "hdfghdfghdfghdfgh";exit;
$getGuarantors = DB::table('guarantors')
->select(['guarantors.id'])
->leftJoin('legalpursuit', 'guarantors.legalpursuit_id', '=', 'legalpursuit.ID')
->where('legalpursuit.ID', '=', $id)
->delete();
//dd($getGuarantors);
//$getGuarantors->delete();
}
if($request->input('REMOVE_FILES')){
$getCurrentFiles = DB::table('files')
->select(['files.ID'])
->leftJoin('legalpursuit', 'files.legalpursuit_id', '=', 'legalpursuit.ID')
->where('legalpursuit.ID', '=', $id)
->delete();
}
LegalPursuit::where('ID',$id)->update(
$request->only(
[
'BRANCH_ID',
'MAIN_ACCOUNT_ID',
'DEPOSITOR_ID',
'ACCOUNT_HOLDER',
'FOLLOW_UP_DATE',
'CURRENT_SCREEN_BALANCE',
'CURRENCY',
'TRL_EQUIVALENT',
'DATE_OF_ATTORNEY_SUBMISSION',
'PROVISION',
'PROVISION_DATE',
'LAWSUIT_ID',
'ASSURANCE',
'DEED_PLATE',
'APPRAISAL_VALUE',
'LIEN_PRICE',
'DETERMINED_GUARANTEES',
'LEVY_INFO',
'LAST_STATUS'
]
)
);
if($request->hasFile('FILES')) {
foreach ($request->file('FILES') as $fl) {
$fileName = time().'_'.$fl->getClientOriginalName();
$fileExt = $fl->getClientOriginalExtension();
$filePath = $fl->store('public/files');
$filex = new Files;
$filex->legalpursuit_id = $id;
$filex->name = $fileName;
$filex->type = $fileExt;
$filex->label = $filePath;
$filex->descript = $fileName.'-'.$fileExt.'--'.$filePath;
$filex->status = 'on';
$filex->save();
}
}
return redirect()->back()->with('success', 'Kayıt Başarılı Bir Şekilde Güncellendi...');
}
I have two tables. the first table is tb_mhs and the second user.
how do you make the id_user in the tb_mhs table the same as the id_user in the user table?
thank you very much for your attention
tb_mhs
user
Controller Code :-
$email = $this->input->post('email');
$nama = $this->input->post('nama');
$password = SHA1($this->input->post('password'));
$data1 = array(
'email'=>$email,
'password'=>$password,
'nama'=>$nama,
'level'=>2,
'status'=>0
);
$i=$this->input;
$npm = $this->register_m->create('user',$data1);
$data = array(
'email' => $i->post('email'),
'password' => SHA1 ($i->post('password')),
'npm' => $i->post('npm'),
'nama' => $i->post('nama'),
'j_kelamin' => $i->post('j_kelamin'),
'kelas_id' => $i->post('kelas_id'),
'angkatan_id' => $i->post('angkatan_id'),
'internal_id' => $i->post('internal_id'),
'eksternal_id' => $i->post('eksternal_id'),
'latitude' => -6.873776,
'longitude' => 107.575639,
'berkas' => $i->post('berkas'),
);
// $insert = $this->register_m->create('user',$data1);
$insert1 = $this->register_m->create('tb_mhs',$data);
$this->session->set_flashdata('sukses', 'Data Registrasi Berhasil di Tambahkan');
redirect(base_url('register/viewdataregistrasi'), 'refresh');
}
}
Model
public function create($table, $data)
{
$query = $this->db->insert($table, $data);
return $this->db->insert_id();
}
CI has Query Helper function call $this->db->insert_id(), it returns the insert ID number when performing database inserts.
After the line
$npm = $this->register_m->create('user',$data1);
Add this code
$newUserID = $this->db->insert_id();
Then update your $data array like this
$data = array[
'id_user' => $newUserID,
'email' => $i->post('email'),
'password' => SHA1 ($i->post('password')),
'npm' => $i->post('npm'),
'nama' => $i->post('nama'),
'j_kelamin' => $i->post('j_kelamin'),
'kelas_id' => $i->post('kelas_id'),
'angkatan_id' => $i->post('angkatan_id'),
'internal_id' => $i->post('internal_id'),
'eksternal_id' => $i->post('eksternal_id'),
'latitude' => -6.873776,
'longitude' => 107.575639,
'berkas' => $i->post('berkas'),
];
Rest of code is good.
For more information Read.
I have this code, what I want to do is to get the primary key lastly inserted into the user table and then put that into the foreign key of the library table. I don't know how to do it with $request or what to do here?
public function register($request = array()) {
$data = array(
'user_name' => $request['username'],
'password' => $request['password'],
'email' => ($request['email'])
);
$data1 = array(
'user_id' => '5',// this is where I have to put the primary key from last table
'library_name' => $request['lib_name']
);
$this->model->insert('user', $data);
$this->model->insert('library', $data1);
$this->redirect('uploadSongs.php');
}
Use mysql_insert_id()
-- Returns the value generated for an AUTO_INCREMENT column by the previous INSERT or UPDATE statement.
You can do like this
public function register($request = array()) {
$data = array(
'user_name' => $request['username'],
'password' => $request['password'],
'email' => ($request['email'])
);
$this->model->insert('user', $data);
$user_id = $this->model->select('user', $data); //select user_id from db
$data1 = array(
'user_id' => $user_id ,
'library_name' => $request['lib_name']
);
$this->model->insert('library', $data1);
$this->redirect('uploadSongs.php');
}
you can do it like this
public function register($request = array()) {
$data = array(
'user_name' => $request['username'],
'password' => $request['password'],
'email' => ($request['email'])
);
$data1 = array(
'library_name' => $request['lib_name']
);
$this->model->insert('user', $data);
$user_id = mysql_insert_id();
$data1['userid'] = $user_id;
$this->model->insert('library', $data1);
$this->redirect('uploadSongs.php');
}
If you are using any frameworks. then they have the helper functions to get last insert id, you should use them
Thanks guys, it worked all i needed to do was just to change the logic, I was using it stupidly and didn't see where to place the insert query so Its working now all i had to do was just to change the place of the insert query as given
public function register($request = array()) {
$data = array(
'user_name' => $request['username'],
'password' => $request['password'],
'email' => ($request['email'])
);
$this->model->insert('user', $data);
$data1 = array(
'user_id' => mysql_insert_id(),// now it works as insert has been done above ....
'library_name' => $request['lib_name']
);
$this->model->insert('library', $data1);
$this->redirect('uploadSongs.php');