How to save in multiple tables Laravel - php

I want to do insertData in both tables together using the Query Builder in the Laravel 5.7 framework. But I found an input error so that only the first table of data can enter and some data in the second table cannot enter. Please help to resolve this problem
I have two tables. The first table is the Organizer table, where later the ID in the Organizer table will be entered into the Users table in the userable_id field and userable_type will be loaded with the string: 'organizer'
OrganizerController.php
public function store(Request $request)
{
$request->validate([
'identity_id' => 'required|string|unique:organizers',
'full_name' => 'required|string|max:191',
'address' => 'required|string',
'photo' => 'required',
'email' => 'required|string|email|max:191|unique:users',
'password' => 'required|string',
'home_phone' => 'numeric',
'mobile_phone' => 'numeric',
'line_id' => 'string',
'facebook_id' => 'string',
'instagram_id' => 'string',
'website_link' => 'string',
'status' => 'required|boolean',
'userable_id' => 'required|numeric',
'userable_type' => 'required|string'
]);
$result = $this->organizerService->postData($request);
return $result;
}
OrganizerService.php
public function postData($params)
{
try {
if (isset($params['photo']) && $params['photo'] != '') {
$photoName = 'organizers_' . $params['identity_id'] . '_' . date('YmdHis') . '.png';
$photoPath = Organizer::PhotoDir;
$imgPath = move_uploaded_file($photoName, public_path() . '/app/' . $photoPath);
unlink($imgPath);
}
$organizers = Organizer::create([
'identity_id' => $params['identity_id'],
'full_name' => $params['full_name'],
'address' => $params['address'],
'photo' => $photoName,
'home_phone' => $params['home_phone'],
'mobile_phone' => $params['mobile_phone'],
'line_id' => $params['line_id'],
'instagram_id' => $params['instagram_id'],
'facebook_id' => $params['facebook_id'],
'website_link' => $params['website_link'],
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s')
])->save();
if (isset($params['userable_type']) && $params['userable_type'] != '') {
$userableType = 'organizers';
}
if (isset($params['userable_id']) && $params['userable_id'] != '') {
$userableId = $organizers->id;
}
DB::table('users')->insert([
'email' => $params['email'],
'password' => Hash::make($params['password']),
'userable_id' => $userableId,
'userable_type' => $userableType,
'status' => $params['status'],
'created_at' => $organizers->created_at,
'updated_at' => $organizers->updated_at
]);
$this->response['status'] = self::SUCCESS_STATUS;
$this->response['message'] = self::SUCCESS_MESSAGE;
$this->response['result'] = $params;
} catch (\Exception $e) {
$this->response['result'] = $params;
$log = ['Service' => 'OrganizerService', 'function' => 'postDataOrganizer', 'params' => $params];
// logError($e, $log);
}
return $this->response['result'];
}
Before inserting data data validation is done so that only userable_id data is not input. After I did insert data, to field userable_id not have an id of the table Organizer with the following message
errors: {userable_id: ["The userable id field is required."]}
userable_id: ["The userable id field is required."]
0: "The userable id field is required."
message: "The given data was invalid."
If I try to remove userable_id validation, the insert results are accepted like this
{
address: "1"
created_at: null
email: "1#mail.com"
facebook_id: "1"
full_name: "1"
home_phone: 1
id: null
identity_id: "1111111"
instagram_id: "1"
line_id: "1"
mobile_phone: 1
password: "11111111111"
photo:'test.jpg'
status: "1"
updated_at: null
userable_id: null
userable_type: "organizer"
website_link: "1"
}
I have also tried using Eloquent method only and mixing it but still not found results. Please help :)

Related

Indirect modification of overloaded element of App\Models\ has no effect

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]);
}

Laravel update table

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
]);

SQLSTATE[22007]: Invalid datetime format: 1366 Incorrect integer value: problem

public function store(Request $request)
{
$this->validate($request,[
'title' => 'string|required',
'summary' => 'string|nullable',
'is_parent' => 'sometimes|in:1',
'parent_id' => 'nullable',
'status' => 'nullable|in:active,inactive'
]);
$data=$request->all();
$slug=Str::slug($request->title);
$count=Category::where('slug',$slug)->count();
if($count>0){
$slug=$slug.'-'.date('ymdis').'-'.rand(0,999);
}
$data['slug']=$slug;
// return $slug;
$status=Category::create($data);
if($status){
request()->session()->flash('success','Kategori başarıyla eklendi');
}
else{
request()->session()->flash('error','Kategori eklenirken hata oluştu');
}
return redirect()->route('category.index');
}
SQLSTATE[22007]: Invalid datetime format: 1366 Incorrect integer value: 'active' for column kintshop.categories.parent_id at row 1 (SQL: insert into categories (title, summary, is_parent, parent_id, photo, status, slug, updated_at, created_at) values (dsadasd, dsadasdas, 1, active, /storage/photos/1/category1.png, active, dsadasd, 2021-06-04 13:09:04, 2021-06-04 13:09:04))
Here is my schema
**Schema::create('categories', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->string('slug')->unique();
$table->string('photo')->nullable();
$table->boolean('is_parent')->default(true);
$table->unsignedBigInteger('parent_id')->nullable();
$table->enum('status',['active','inactive'])->default('active');
$table->foreign('parent_id')->references('id')->on('categories')->onDelete('SET NULL');
$table->mediumText('summary')->nullable();
$table->timestamps();
});**
Error is clear .Request contain parent_id value active but migration file says parent_id is foreign key you must pass accurate value to create method.
parent_id data type is Big Integer
See your $request->all() data
[▼ "_token" => "LrDekkz85cys4ZFx4vCFmy0VPHwFCh1u7aPIcEqq"
"title" => "dsadasd"
"summary" => "<p>dsadasdas</p>"
"files" => null
"is_parent" => "1"
"parent_id" => "active"
"photo" => "/storage/photos/1/category1.png"
"status" => "active" ]
So better update validation rule for parent_id contain only integer
Table column 'parent_id' is bigInteger but you have 'active' (string) in your request, so, change data type on DB or update validation rules.
TIP: don't use '$request->all()', is not safe.. you can use instead '$request->only('title', 'summary', 'status' .....)'. This is a safe practice to retrieve params from request
$this->validate($request,[
'title' => 'string|required',
'summary' => 'string|nullable',
'is_parent' => 'sometimes|in:1',
'parent_id' => 'nullable',
'status' => 'nullable|in:active,inactive'
]);
This is wrong...$this->validate([]) accept the rules first as argument, not the request. Maybe you must do
$request->validate([
'title' => 'string|required',
'summary' => 'string|nullable',
'is_parent' => 'sometimes|in:1',
'parent_id' => 'nullable',
'status' => 'nullable|in:active,inactive'
]);
or
$validation = Validator::make($request->all(),[rules]);

CakePHP Save Primary Key of associated table as Foreign Key of another

So i'm currently figuring out how to add users. Adding an email record then using the Auto-incremented Emails id to assign to email_id in Users table with that id being a dependent.
I'm doing it all from the users controller
public function add()
{
if ($this->request->is('post')) {//specify we are getting PostData
$data = [
//'id' => '111',
'address' => $this->request->data['Emails']['address'],
'created' => Time::now(),
'last_modified' => Time::now(),
'last_contacted' => Time::now() ];
$emails = TableRegistry::get('Emails');
$email = $emails->newEntity($data, [ 'associated' => ['Users']]);
$save = $emails->save($email, ['associated' => 'Users']);
$email_id = $save->id;
$users = TableRegistry::get('Users');
$user = $users->newEntity($this->request->getData(), ['associated' => ['Emails.id']]);
$user->dob = date('Y-m-d', strtotime($user->dob));
$user->email['id'] = $email_id;
$user->is_admin = 'n';
$user->last_login = Time::now();
$user->created = Time::now();
$user->last_modified = Time::now();
if ($emails->save($email, ['associated' => 'Users'])) {
if($users->save($user, ['associated' => 'Emails'])) {
$this->Flash->success(__('The user has been saved.'));
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error(__('User could not be saved. Please, try again.'));
}
}else {
$this->Flash->error(__('Email save failure, please try again.'));
}
}
$emails = $this->Users->Emails->find('list', ['limit' => 200]);
$this->set(compact('user', 'emails'));
$this->set('_serialize', ['user']);
}
which takes data in from the form:
` Form->create( ) ?>
<?php
echo $this->Form->control('Emails.address', ['required' => true, 'label' => 'Email']);
echo $this->Form->control('Users.password', ['required' => true, 'label' => 'Password']);
echo $this->Form->label('Gender');
echo $this->Form->radio('Users.gender',['m'=>'Male', 'f' => 'Female'] , [ 'required' => true]);
echo $this->Form->control('Users.family_name', [ 'required' => true, 'label' => 'Given Name']);
echo $this->Form->control('Users.given_name', [ 'required' => true, 'label' => 'Family Name']);
echo $this->Form->control('Users.dob', [ //birth date between 1900 and current year
'data-format'=>'d m Y',
'class' => 'dateinput',
'required' => true,
'data-default-date'=> '03-30-1993',
'maxYear' => date('Y') - 17,
]);
echo $this->Form->control('Users.phone', [ 'required' => true]);
?>
</fieldset>
<?= $this->Form->button(__('Submit'), ['class'=>'text-right']) ?>
<?= $this->Form->end() ?>`
SO my problem is that i can create email addresses and make them save - great.
EMails and Users are a hasOne. defined in emails table
`$this->hasOne('Users', [
'foreignKey' => 'emails_id', 'bindingKey' => 'id', ])
->setDependent(true)
->setName('Emails');
`
I just cant seem to take the users input and add that into the table. Errors include:
Cannot marshal data for "Emails" association. It is not associated with "Users" which happens when i only put the hasone in the UsersTable. Same if I only have it in EmailsTable. Dp it when the other model contains the fk
ERROR 1452: Cannot add or update a child row: a foreign key constraint fails which happens when both have hasOne in it and i make the email first. It still says theres no fk relation

Error "No function matches the . . ." Laravel Transaction With PostgreSQL

I using laravel 5.3 with PostgreSQL and i have code like this
public function store(array $request)
{
DB::transaction(function () use ($request) {
$phoneData = [
'phone_no' => $request['phone'],
'created_by' => $request['sdm_employee_id'],
'updated_by' => $request['sdm_employee_id'],
'created_stamp' => Carbon::now()->toDateString(),
'updated_stamp' => Carbon::now()->toDateString(),
];
$phone = DonorPhone::create($phoneData);
if (!$phone) {
throw new \Exception('Phone not created for account');
}
$data = [
'phone_id' => $phone->id,
'full_name' => $request['name'],
'address' => $request['address'],
'email' => array_key_exists('email', $request) ? $request['email'] : null,
'register_date' => Carbon::now()->toDateString(),
'marketer_id' => (int) $request['sdm_employee_id'],
'created_by' => (int) $request['sdm_employee_id'],
'updated_by' => (int) $request['sdm_employee_id'],
'company_id' => 2,
'user_status' => 1,
'note' => 'Add donor from sales track apps',
'phone_no_full' => $request['phone'],
'created_stamp' => Carbon::now()->toDateString(),
'updated_stamp' => Carbon::now()->toDateString(),
];
$contact = self::create($data);
if (!$contact) {
throw new \Exception('Contact not created');
}
$phone->user_id = (int)$contact->id;
$phone->save();
$target = new Target;
$target->updateAchievement($data['sdm_employee_id'], $this->tragetType, Carbon::now()->year, Carbon::now()->month);
throw new \Exception('Contact not created');
});
}
When create contact i got error
SQLSTATE[42883]: Undefined function: 7 ERROR: function php_donor_phone_get_all(integer) does not exist\nLINE 1: SELECT php_donor_phone_get_all(NEW.id)\n ^\nHINT: No function matches the given name and argument types. You might need to add explicit type casts.\nQUERY: SELECT php_donor_phone_get_all(NEW.id)\nCONTEXT: PL\/pgSQL function public.php_donor_tr_full_text() line 6 at assignment (SQL: insert into \"public\".\"php_donor_personal\" (\"full_name\", \"address\", \"email\", \"register_date\", \"marketer_id\", \"created_by\", \"updated_by\", \"company_id\", \"user_status\", \"phone_no_full\", \"created_stamp\", \"updated_stamp\") values . . .
I check for function php_donor_phone_get_all is exist and my database username have a grant to execute this function. This seems to relate to a specific data type when calling the function, passing not an integer, but I do not know how to ensure that data in passing is an integer. There is a hint for me? Please help.

Categories