cakephp save with new association record - cakephp-3.x

I have a trouble with save association data.
I want to add a new record to associated table.
For example, I have a User and Friend Model.
User Model has a [id, gender, age, hobby]
Friend Model has a [id, name, age, hobby]
My Table Data is below.
User|id|gender|age|hobby|
1 |1 |male |24 |sport|
Friend|id|gender|age|hobby|
1 |1 |male |24 |sport|
My Code is below.
$users = $this->Users->find()->contain(['Friends'])->where(['User.id' => $id])->first();
$data = $user->toArray();
$data['Friends'][1]['gender'] = 'male';
$data['Friends'][1]['age'] = 25;
$data['Friends'][1]['hobby'] = 'fishing';
$users = $this->Users->patchEntity($users, $data, 'associated' => ['Friends']);
$flag = $this->Users->save($users);
There is no problem when I edit existing data. But new data is not appended my database.
Anyone has any idea? Thank you very much.

Related

store data from conroller to database in laravel

Am getting data from two tables banks one has bank details and another has cheques. the cheques table has bank_id column where by i loop through and calculate the totals of each bank.
How can i store the data in a table instead of it staying in a variable.
I have a controller to calculate the totals;
$banks_data = Bank::all();
$banks_totals = [];
foreach ($banks_data as $bank){
$totals = InsuranceCheque::where('bank_id', $bank->id)->sum('amount');
array_push($banks_totals,
[
'id'=>$bank->id,
'name'=> $bank->name,
'description' =>$bank->description,
'amount'=>$totals,
'created_at'=>$bank->created_at,
]);
}
but how will i be able to access the data in a different controller?
Which table do you want to save it to? Assuming you have a model BankTotal that handles the table bank_totals, you can do this
$banks_data = Bank::all();
$banks_totals = [];
foreach ($banks_data as $bank){
$totals = InsuranceCheque::where('bank_id', $bank->id)->sum('amount');
array_push($banks_totals,
[
'id'=>$bank->id,
'name'=> $bank->name,
'description' =>$bank->description,
'amount'=>$totals,
'created_at'=>$bank->created_at,
]);
}
BankTotal::insert($bank_totals);//Bulk insert
I did not understand the second part of the question on "but how will i be able to access the data in a different controller?"
But you can access the data from another controller by querying the model:
BankTotal::all();

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

Insert/create data using belongsTo Relation in laravel

Phone BelongsTo User. Now how i insert phone & user data both through belongsTo Relationship & auto get user_id foreign key in phone table. Here I try this code but not work.
$phoneData = $request->get('phone');
$userData = $request->get('name');
$phone->user()->create($userData);
$phone->create($phoneData);
Here is in form input field
Something like this:
$userData = $request->get('name');
$phoneData = $request->get('phone');
$user = User::create($userData);
$user->phones()->save(new Phone($phoneData));
Of course you'll need to define the relationship on the User model as well:
// \App\User.php
public function phones()
{
return $this->hasMany(\App\Phone::class);
}
You can't create a phone without an user, it's not recommended because the foreign key constraint, that you must have in your database, won't let you..
$userData = $request->get('name');
$phoneData = $request->get('phone');
$phone = new Phone();
$phone->user()->associate(User::create($userData));
$phone->save();
Maybe you are looking for something like this...
for updating..
$phone = isset($phoneData['id'])
? Phone::where('id', $phoneData['id'])->first() : new Phone();
$phone->user()->associate(User::firstOrCreate(
['email' =>$userData['email']], .... extra data from user));
$phone->save();

Laravel aggregate function within single query

I have a User model with a table as users(id, email, password, gender, status)
I want to list the users based on condition along with the gender counts, here is my code:
$users = App\User::where('status', '1');
$users = $users->orderBy('email');
$data['all_users'] = $users; // all users
$data['total_males'] = $users->where('gender', 'M')->count(); // male count
$data['total_females'] = $users->where('gender', 'F')->count(); // female count
return view('users.list', $data);
The above code does not returns all the users on the view and filters gender, even when I have already passed the result object $users to the $data array.
Off course, I can set a male_count and female_count variables on the view and increment it based on the conditions like if (gender == 'M') total_males++ and display out of the loop.
What I am doing wrong here?
The proper way to do your eloquent queries on your controller and pass the data to the view would be:
$users = App\User::where('status', '1')->orderBy('email')->get();
$data['all_users'] = $users; // all users
$data['total_males'] = App\User::where('gender', 'M')->count(); // male count
$data['total_females'] = App\User::where('gender', 'F')->count(); // female count
return view('users.list', $data);
Just a simple thing, that I forgot! I have a habit of putting get() function on the view: :p
$data['all_users'] = $users->get(); // all users
$data['total_males'] = $users->where('gender', 'M')->count(); // male count
$data['total_females'] = $users->where('gender', 'F')->count(); // female count
You didn't called get method. Please try
$data['all_users'] = $users->get(); // all users
The Eloquent didn't execute, because nothing get or count method in there
$data['all_users'] = $users->count(); // all users

Laravel Copy record and duplicate with new values

How can i copy a record and save it with a different value for 1 or more field?
for example:
get----> first_name, last_name, civil_status, work
i want to copy the first name, and last name then insert it with a new civil status and work.
You could use the replicate method of model like this:
// Retrieve the first task
$task = Task::first();
$newTask = $task->replicate();
$newTask->project_id = 16; // the new project_id
$newTask->save();
You could use replicate method. This will create a new object with the same values except the primary key, and the timestamps. After that you can save your model:
$task = Task::find(1);
$new = $task->replicate();
If you want you could change a property
$new->project = $otherProject;
and then
$new->save();
if you want the new ID, easy:
$newID = $new->id;
You can use replicate() and then update that row:
Model::find(1)->replicate()->save();
$model = Model::find(1);
$model->project_id = $new_project_id;
$model->save();
also you can do like this.
$selected = Model::find(1);
$copy = $selected->replicate()->fill(
[
'project_id' => $new_project_id,
]
);
$copy->save();

Resources