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.
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]);
}
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
]);
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 :)
I have this model factory that generates new contact, it uses random company_id:
$factory->define(App\Models\Contact::class, function (Faker\Generator $faker)
{
$company_id = Company::all()->random()->id;
return [
'firstname' => $faker->firstName,
'lastname' => $faker->lastName,
'phone' => $faker->phoneNumber,
'email' => $faker->email,
'company_id' => $company_id,
'lead_id' => \App\Models\Lead::where('company_id', $company_id)->get()->random()->id,
];
});
It is ok when I use it in seeds:
factory(App\Models\Contact::class)->create();
But for testing I need somehow to pass $company_id to factory, create contact for concrete company_id (I know that I can do ->create(['company_id', $company_id])) but this will rewrite only company_id from Contact.
When I select lead_id, I also need to know current company_id.
How to pass company_id to factory as parameter?
Try to use this example:
$factory->define(App\Models\Contact::class, function ($faker, $params) {
$company_id = $params['company_id'];
....
});
and this to make a new object:
$newContact = factory(App\Models\Contact::class)->make(['company_id' => $current_company_id]);
Depends on your Laravel version it will be different.
For laravel 5.1
https://github.com/laravel/framework/issues/9245
You will need to check if is passed manually
// Testcase
$company = factory(App\Models\Company::class)->create();
factory(App\Models\Contact::class)->create(['company_id' => $company->id]);
// Factory
$factory->define(App\Models\Contact::class, function (Faker\Generator $faker, $attribues) {
// Manually check if id is passed
$company_id = (isset($attribues['company_id'])) ?: Company::all()->random()->id;
return [
'firstname' => $faker->firstName,
'lastname' => $faker->lastName,
'phone' => $faker->phoneNumber,
'email' => $faker->email,
'company_id' => $company_id,
'lead_id' => \App\Models\Lead::where('company_id', $company_id)->get()->random()->id,
];
});
For Laravel 5.2 and above you can simply pass id
https://laravel.com/docs/5.5/database-testing#relationships
// Testcase
$company = factory(App\Models\Company::class)->create();
factory(App\Models\Contact::class)->create(['company_id' => $company->id]);
// Factory
$factory->define(App\Models\Contact::class, function (Faker\Generator $faker, $attribues) {
// Manually check if id is passed
$company_id = (isset($attribues['company_id'])) ?: Company::all()->random()->id;
return [
'firstname' => $faker->firstName,
'lastname' => $faker->lastName,
'phone' => $faker->phoneNumber,
'email' => $faker->email,
'company_id' => function(){
return factory(\App\Models\Company::class)->create()
},
'lead_id' => \App\Models\Lead::where('company_id', $company_id)->get()->random()->id,
];
});
So, for your case, get your random company_id first and pass it to factory. Depends on your Larval version change the ContactModel factory. Or if you have relation that you can query, you can do it as well.
// If you have a relation
$contact = factory(App\Models\Contact::class)->create();
$company_id = $contact->company->id;
I'm building a small application in Laravel 5.5 where I'm having two models: Interaction and Interaction Summary in my Interaction model I'm having following relationship:
public function meetingSummaries()
{
return $this->hasMany('App\InteractionSummary');
}
Now to create the interaction I'm using following in my controller:
$data = $request->only('user_id', 'event_type', 'schedule', 'summaries', 'type', 'venue', 'with_client');
$data['schedule'] = Carbon::parse($request->schedule)->addHours(5)->addMinutes(30)->toDateTimeString();
$meeting = [];
$meeting['user_id']= $data['user_id'];
$meeting['schedule'] = $data['schedule'];
$meeting['type'] = $data['type'];
$meeting['with_client'] = $data['with_client'];
$meeting['venue'] = $data['venue'];
$meeting['event_type'] = $data['event_type'];
$interaction = Interaction::create($meeting);
if($data['summaries'])
{
$container = [];
foreach($data['summaries'] as $summary)
{
$summary = (Object)$summary;
if($summary->client['label'])
{
$container[] = new InteractionSummary([
'company_id' => $summary->client['label'],
'nature' => $summary->type,
'user_id' => $summary->mention['label'],
'action' => $summary->action,
'feedback' => $summary->comment
]);
}
}
}
$interaction->meetingSummaries()->saveMany($container);
}
But while updating I don't know to overcome this, as in my fields there might be new or old relational data. I'm trying something like this:
if($data['summaries'])
{
$container = [];
foreach($data['summaries'] as $summary)
{
$summary = (Object)$summary;
if($summary->id)
{
$container[] = new InteractionSummary([
'id' => $summary->id,
'company_id' => $summary->client['value'],
'nature' => $summary->type,
'user_id' => $summary->mention['value'],
'action' => $summary->action,
'feedback' => $summary->comment
]);
}
else {
$container[] = new InteractionSummary([
'company_id' => $summary->client['value'],
'nature' => $summary->type,
'user_id' => $summary->mention['value'],
'action' => $summary->action,
'feedback' => $summary->comment
]);
}
}
$interaction->meetingSummaries()->save($container);
}
Which is sending me error:
Type error: Argument 1 passed to Illuminate\Database\Eloquent\Relations\HasOneOrMany::save() must be an instance of Illuminate\Database\Eloquent\Model, array given, called in ~\app\Http\Controllers\InteractionsController.php on line 449
If I do:
$interaction->meetingSummaries()->saveMany($container);
I get repeated new fields.
Guide me how to overcome this. Thanks.
Use the findOrNew() method:
$summaryItem = InteractionSummary::findOrNew($summary->id);
$summaryItem->fill([
'company_id' => $summary->client['value'],
'nature' => $summary->type,
'user_id' => $summary->mention['value'],
'action' => $summary->action,
'feedback' => $summary->comment
]);