After Update, The data from another Table will be deleted - laravel

I Have two different database table named Customers and Change_info_request
customers will request of changing their infomation and it will stored in Change_info_request and me the admin will be the one who will approve for changing information.
after the update the information inside the Change_info_request will transfer to the Customers table and the data inside the Change_info_request will be deleted .
And that's is my problem, i want to do it in the same controller like this
UpdateRequest
public function UpdateRequest(ClientUpdate $request){
$res = Customer::where('id', $request->id)
->update([
'first_name' => $request->new_first_name,
'last_name' => $request->new_last_name,
'birthdate' => $request->new_birthdate,
'gender' => $request->new_gender,
'pending_update_info' => 2,
]);
if($res) {
return response()->wrap($res);
} else {
return response()->wrap(["message" => "something went wrong!"]);
}
}
How will i delete the info from Change_info_request inside this controller ?
Sorry for the wrong grammar and im only a student that studying laravel.

you have id of that row in Change_info_request table right?
i have done this before this was my way:
i store new information in my table called edit-user (just like your Change_info_request ) and when i show them in admin dashboard i have their id!
when admin click on approve button it will send the id of that row to some function!
in function i find the row in edit-user table with id that i have, and replace my new data in my users table (your Customers table) and when i finished replacing data i will delete data from edit-user with that id!
Change_info_request::find('customer_id', $id)->delete();
with id of that row in edit-user(your Change_info_request table) table you can do anything
and of course your in Change_info_request table you should have user_id field
good luck!

Before your if condition, you can add something like:
$del = Change_info_request::find('customer_id', $request->id)->delete();

Related

Laravel 8.0 facing issue while trying to update a table with vue form, 'Attempt to read property \"item_id\" on null'

So, i have a table called Items table and another table called item_quantities, on item_quantities ive a column named item_id which is connected to items table id. All the fillable properties on both tables are all in one form on the frontend, and i take care of the form fields on the backend
Whenever i try to update the quantity on the form which is from item_quantities's table with a form, i'm facing serious issue updating the item_quantities. getting Attempt to read property "item_id" on null.
It all started when i noticed a duplicate entries on the item-quantities table, so i deleted all the datas on it..
Here's is the form screenshot
The vue form
and the backend logic
public function saveData(Request $request, $id) {
// dd($request->name);
$updateGroceries = Item::where('id', $request->id)->get()->first();
$updateGroceries->update([
'name' => $request->name,
'description' => $request->description,
'price' => $request->price,
]);
if($updateGroceries) {
$item_quantity = ItemQuantity::where('item_id', $updateGroceries->id) ?
ItemQuantity::where('item_id', $updateGroceries->id)->get()->first() :
new ItemQuantity;
if($item_quantity->item_id == null) {
$item_quantity->item_id = $updateGroceries->id;
}
$item_quantity->quantity = $request->quantity;
$item_quantity->save();
}
}
I'M SO SORRY IF MY ENGLISH WAS'NT CLEARED ENOUGH
Thanks in anticipation
You can simply use firstOrNew() method. This will first find the item, if not exist create e new instance.
$item_quantity = ItemQuantity::firstOrNew(['item_id' => $updateGroceries->id]);
$item_quantity->quantity = $request->quantity;
$item_quantity->save();
Note that the model returned by firstOrNew() has not yet been persisted to the database. You will need to manually call the save method to persist it.
Actually your errors workflow as that:
$item_quantity=null;
$item_quantity->item_id;
You can do that with optional global helper:
optional($item_quantity)->item_id ?: 'default value';

Laravel unique validation on update not working by passing id in validation

In my controller i am inserting data in three different table at a time.
I have put validation before inserting in some of the unique fields. But at the time of Update it says email already exists. I have searched a lot and got a solution which is working for everyone except for me by passing id in validation rule.
I have tried
$this->validate($request,[
'admission_no'=>"required|unique:students,admission_no,$id",
'student_email=>"required|unique:students,student_email,$id",
'guardian_email'=>"required|unique:student_parents,guardian_email,$id"
]);
$student = Student::find($id);
$student->admission_no = $request->admission_no;
$student->student_email = $request->student_email;
$student->save();
//parent model
$parent = StudentParent::where('student_id',$student->id)->first();
$parent->guardian_email = $request->guardian_email;
$parent->save();
It doesn't work this way i dont know why
also the main problem is StudentParent model is different how to pass id in validation for this model to unique update
Your students and student_parents table has different $id, So you need to pass student_parents table id on guardian_email validation :
$validatedData = $request->validate([
'admission_no'=>"required|unique:students, admission_no, $id", // expect students table id
'student_email'=>"required|unique:students, student_email, $id", // expect students table id
'guardian_email'=>"required|unique:student_parents, guardian_email, $student_parents_id" // pass student_parents table id here
]);
Hope this helps

laravel tables with relationship and insertion

I have 4 tables
Customers : with data of customers. this table hasMany(Refunds)
Refunds: with data of various request. this table belongsTo(Customers) AND belongsToMany(Services)
Services: with list of services. this table belongsToMany(Refunds)
Refunds-Services: bridge table for refunds and services
I have a form that must insert datas in the correct table.
public function storeRefunds(RefundsPost $request){
DB::beginTransaction();
$customers = Customers::create($request->all());
$refunds = $customers->refunds()->create([
'date_ref' => request('date_ref'),
'status_ref' => request('stato'),
]);
$tipo = $request->input('tipo', []);
$importo = $request->input('importo', []);
$refunds = Refunds::create($request->all());
for ($i=0; $i < count($tipo); $i++) {
if ($tipo[$i] != '') {
$refunds->services()->attach($tipo[$i], [
'services_id' => $tipo[$i],
'services_amount' => $importo[$i]
]);
}
}
return redirect("/");
}
with this code i can insert all datas in correct tables but i cannot find ID connection in the Refunds table. Two different ID are created in Refunds table. second created id in the Refunds table not connected to any customer (0) but connected to the list of services choosen.
How can i do?
Thx
You need to debug your code. First Refund creates in this line $refunds = $customers->refunds()->create and it's belongs to Customer, second Refund creates here : $refunds = Refunds::create($request->all()); and it's doesn't relate to any Customer, but relates to Service (you do this in for loop). By the way, your tipo input is not multiple (it should be with [] if you expects it can be more than one value) and for loop is senseless in this sutiation.
Delete one of Refunds::createmethods, bring your data to expected view and use createMany() method.
More info in Laravel docs : https://laravel.com/docs/7.x/eloquent-relationships#the-create-method

How to check the data already exists or not laravel

I have 2 tables. Patient table and reservation table.
Patient table:
ID
name
medical record number (norekmed)
Table of reservations
ID
idpatient
idroom
How do I check patient data already or not if I make a reservation?
Checking is by comparing between a reservation form field with norekmed in the patient table.
If patient data already exists, we can make a reservation. And if there is no patient data, we cannot make a reservation.
If it turns out this is not good, and there is a better method, I accept that.
Reservation controller (store)
$this->validate($request,
[
'idpatient' => 'required|unique:reservation,idpatient',
'idroom' => 'required',
]);
Patient::where(function($query) {
$query->has('id')
->orHas('norekmed');
})->find(1);
$reservasi = new Reservasi();
$reservasi->idpatient = $request->idpatient;
$reservasi->idroom = $request->idroom;
$reservasi->save();
A simple solution could be to use firstOrCreate and let the validator check if the patient id and room id exist. If I would have done this I would do the following:
$this->validate($request, [
// This will check if the patient exists.
'idpatient' => 'required|exists:patients,id',
// This will check if the room exists.
'idroom' => 'required|exists:room,id',
]);
// Get the reservation or create one if it does not exist.
$reservasi = Reservasi::firstOrCreate([
'idpatient' => $request->idpatient,
'idroom' => $request->idroom,
]);
...

cakePHP 3 save data in Many to Many relationship

I have Employees and Complexes in a Many to many relationship.I have used the
bake console to generate models, controllers... for Employees and Complexes tables.
My questions is :
-Since I have in my BD The table "complexes_employees", do I have to bake also Model
and controller for this Table too or cakePHP is able to know that it contains the
two foreign keys of Employees and Complexes.
Second question :
-How can I save my data in this Three tables. for my app I have to save employees
per Complex .
// Employees Controller
public function addEmpPerComplex($id_complex){
$emp = $this->Employees->newEntity();
if ($this->request->is('post')) {
$employee = $this->Employees->patchEntity($employee, $this->request->data, ['associated'=>['Complexes._joinData']] );
//here I need to insert the record that contains the employee data in Employees Table
// then I need to insert in "complexes_employees" the ID of Complex sended in parametre of this function and the ID of the new Employee
Thanks for helping me
Do I have to bake also Model and controller for this Table?
No, CakePHP will use the abstract Table class. However, if you need extra information for this relationship, then you will need to create a join model. Check http://book.cakephp.org/3.0/en/orm/associations.html#using-the-through-option
How can I save my data in this Three tables?
As long as your data has the id of a related entity, it will automatically be saved both entity and relation:
$data = [
//employee data,
'complexes' => [
['id' => $id_complex]
]
]
$this->Employees->patchEntity($employee, $data, [
'associated' => ['Complexes']
]);
/*
Saves both the new Employee and the relation
(employeed id and complex id in complexes_employees)
*/
$this->Employees->save($employee);
For more information: http://book.cakephp.org/3.0/en/orm/saving-data.html#saving-belongstomany-associations

Resources