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...');
}
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]);
}
Please I have an issue with my code. whenever I want to update my post it always says my files are empty although I have an old file. Please can you help me to fix it? Thanks in advance.
This my controller
public function update(Request $request, $id)
{
$allowedOptions = Constants::ACTIVE . ",". Constants::INACTIVE;
$allowedTypes = Constants::MUSIC;
$data = $request->validate([
'category_id' => "required|string",
'name' => 'required|string',
'content_desccription' => 'required:string',
"type" => "required|string|in:$allowedTypes",
"meta_title" => "required|string",
"meta_keywords" => "required|string",
"meta_description" => "required|string",
"is_sponsored" => "required|string|in:$allowedOptions",
"is_top_story" => "required|string|in:$allowedOptions",
"is_featured" => "required|string|in:$allowedOptions",
"is_published" => "required|string|in:$allowedOptions",
"can_comment" => "required|string|in:$allowedOptions",
]);
if (!empty([
$image_path = MediaFilesHelper::saveFromRequest($request->cover_image, "postImages", $request),
$music_path = MediaFilesHelper::saveFromRequest($request->cover_music, "postMusic", $request),
]));
$data['cover_image'] = $image_path;
$data['cover_music'] = $music_path;
$post = Post::where('id', $id)->update($data);
return redirect()->route('admin.post.index')->with('success_meassage', 'Post updated successfully');
}
This is the code handly the file
public static function saveFromRequest($file , $path , Request $request)
{
$file_name = Str::slug($request->name, '-').".".$file->extension();
$file->move(public_path($path) , $file_name);
return $path."/".$file_name;
}
I have changed your file condition now try I hope it work for you now.
public function update(Request $request, $id)
{
$allowedOptions = Constants::ACTIVE . ",". Constants::INACTIVE;
$allowedTypes = Constants::MUSIC;
$data = $request->validate([
'category_id' => "required|string",
'name' => 'required|string',
'content_desccription' => 'required:string',
"type" => "required|string|in:$allowedTypes",
"meta_title" => "required|string",
"meta_keywords" => "required|string",
"meta_description" => "required|string",
"is_sponsored" => "required|string|in:$allowedOptions",
"is_top_story" => "required|string|in:$allowedOptions",
"is_featured" => "required|string|in:$allowedOptions",
"is_published" => "required|string|in:$allowedOptions",
"can_comment" => "required|string|in:$allowedOptions",
]);
if ($request->file('cover_image')) {
$image_path = MediaFilesHelper::saveFromRequest($request->cover_image, "postImages", $request);
$data['cover_image'] = $image_path;
}
if ($request->file('cover_music')) {
$music_path = MediaFilesHelper::saveFromRequest($request->cover_music, "postMusic", $request);
$data['cover_music'] = $music_path;
}
$post = Post::where('id', $id)->update($data);
return redirect()->route('admin.post.index')->with('success_meassage', 'Post updated successfully');
}
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 have a problem, every time I enter or refresh a page it inserts a new record
Controller:
public function cobrar(Request $request,$id){
$data = [
'category_name' => 'datatable',
'page_name' => 'custom',
'has_scrollspy' => 0,
'scrollspy_offset' => '',
];
$cliente = \App\Models\Eventos::first();
$cobros = \App\Models\Cobros::where('turno_id', $request->id)->first();
$evento = \App\Models\Eventos::where('id' , $id)->with('servicio')->first();
$servicio = \App\Models\Servicios::where('id', $evento->servicio_id)->first();
$event = \App\Models\Eventos::find($id);
Cobros::insert([
'turno_id' => $request->input("turno_id"),
'importe' => $request->input("importe"),
'servicio_id' => $request->input("servicio_id"),
]);
return view('cobrar',compact('cobros', 'evento', 'servicio', 'event'))->with($data);
}
Image Database:
I suggest adding a check to see if method is get or post...
public function cobrar(Request $request,$id){
$data = [
'category_name' => 'datatable',
'page_name' => 'custom',
'has_scrollspy' => 0,
'scrollspy_offset' => '',
];
$cliente = \App\Models\Eventos::first();
$cobros = \App\Models\Cobros::where('turno_id', $request->id)->first();
$evento = \App\Models\Eventos::where('id' , $id)->with('servicio')->first();
$servicio = \App\Models\Servicios::where('id', $evento->servicio_id)->first();
$event = \App\Models\Eventos::find($id);
if ($request->isMethod('post')) {
Cobros::insert([
'turno_id' => $request->input("turno_id"),
'importe' => $request->input("importe"),
'servicio_id' => $request->input("servicio_id"),
]);
}
return view('cobrar',compact('cobros', 'evento', 'servicio', 'event'))->with($data);
}
This is the my back-end code. I wrote the test for this function as follows:
public function index(Request $request)
{
$fields = 'in:' . implode(',', Schema::getColumnListing('suppliers'));
$messages = [
'order_by.in' => 'The selected column name is invalid.',
];
$this->validate($request, [
'page' => ['numeric'],
'per_page' => ['numeric'],
'order_direction' => ['in:desc,asc,DESC,ASC'],
'order_by' => [$fields],
], $messages);
$perPage = 10;
$filter = '';
$orderBy = 'id';
$orderDirection = 'DESC';
try {
if ($request->has('per_page')) $perPage = (int)$request->per_page;
if ($request->has('filter')) $filter = $request->filter;
if ($request->has('order_by')) $orderBy = $request->order_by;
if ($request->has('order_direction')) $orderDirection = strtoupper($request->order_direction);
$suppliers = Supplier::select('id', 'firstname', 'lastname', 'phone', 'email', 'custom_field_1', 'custom_field_2')->where('store_id', Auth::user()->store);
if (!!$filter) {
$suppliers->where('id', 'LIKE', "%{$filter}%")
->orWhere('firstname', 'LIKE', "%{$filter}%")
->orWhere('lastname', 'LIKE', "%{$filter}%")
->orWhere('email', 'LIKE', "%{$filter}%")
->orWhere('phone', 'LIKE', "%{$filter}%");
}
$suppliers->orderBy($orderBy, $orderDirection);
$suppliers = $suppliers->paginate($perPage);
return response()->json([
'success' => true,
'data' => $suppliers->toArray(),
], Response::HTTP_OK);
} catch (Exception $e) {
report($e);
return serverExceptionMessage();
}
}
This is what I have tried and test. I'm creating a store because store_id is a foreign key in my supplier table and adding suppliers dynamically and filtering the firstname through the URL and getting the result from seeJson as an array:
public function testSupplierListViewPaginationFilterTest()
{
$user = factory('App\Models\User')->make();
$store = (factory('App\Models\Store')->make())->getAttributes();
$this->actingAs($user)
->post('/create-new-store', $store)
->seeStatusCode(Response::HTTP_OK);
$attributes = [
'id' => 1,
'firstname' => 'ashid',
'lastname' => 'mhd',
'phone' => 776358547,
'email' => 'ashid#email.com',
'custom_field_1' => 'test',
'custom_field_2' => 'test',
];
$user->store = Store::latest()->first()->id;
$attributes['store_id'] = Auth::user()->store;
$supplier = Supplier::create($attributes);
$this->actingAs($user)
->get('/suppliers?filter=' . $supplier['firstname'], $attributes)
->seeStatusCode(Response::HTTP_OK)->seeJson([
'success' => true,
"data" =>
[
'id' => 1,
'firstname' => 'ashid',
'lastname' => 'mhd',
'phone' => 776358547,
'email' => 'ashid#email.com',
'custom_field_1' => 'test',
'custom_field_2' => 'test',
]
]);
}
I'm getting following error:
1) SupplierTest::testSupplierListViewPaginationFilterTest
Unable to find JSON fragment
["data":"custom_field_1":"test","custom_field_2":"test","email":"ashid#email.com","firstname":"ashid","id":1,"lastname":"mhd","phone":776358547}] within [{"data":{"current_page":1,"data":[{"custom_field_1":"test","custom_field_2":"test","email":"ashid#email.com","firstname":"ashid","id":1,"lastname":"mhd","phone":"776358547"}],"first_page_url":"http:\/\/localhost\/suppliers?page=1","from":1,"last_page":1,"last_page_url":"http:\/\/localhost\/suppliers?page=1","next_page_url":null,"path":"http:\/\/localhost\/suppliers","per_page":10,"prev_page_url":null,"to":1,"total":1},"success":true}].
Failed asserting that false is true.
I need a best solution for this problem .