How to associate from a parent model to another - laravel

$user = User::create(['name' => request('name'),
'email' => request('email'),
'password' => bcrypt(request('password')),
'place_id' => request('place_id'),
'role_id' => request('role_id') ,
'status' => request('status')]);
if (request('role_id') === 3) {
$user->courier()->associate($user);
$user->save() ;
}
I want to insert in my couriers table the user_id of that inserted user if it has role_id of 3. I tried this but didn't work.

If you want to associate the user with a particular courier, there must be the corresponding courier. First of all, you have to find it or create a new courier. If you have id of the courier then you can try the following.
$courier = Courier::find($user->id);
$courier->user()->associate($user);
$courier->save();
The above code will update user_id field of the courier with courier_id with the id of $user

Related

Laravel: How to save into two tables , but, the id of the first will be saved into the second as foreign id

I have two tables in laravel, the student and parent, the idea is upon creating a student account, the parent account is auto-generated. However, there are chances, a parent can have two children or more in a school. zo, before saving into the database, it should query the parent table to see if the parent exists, if it exists, fetch the id and save it into the student table, BUT, if the parent does not exist, save the parent into the parent table, thereafter fetch the parent id and save into student table......
sadly, the parent ID is always zero in student id
so far,
$parentt = Parentt::where('phone', '=', $request->parentMobileNumber)->first();
if ($parentt === '') {
$parenttInstance = new Parentt();
$parenttInstance->name = $request->parentName;
$parenttInstance->phone = $request->parentMobileNumber;
$parenttInstance->password = bcrypt($request->password);
$parenttInstance->save();
$parentID = $parenttInstance->id;
}else {
$parentID = $parentt->pluck('id');
}
}
$data = array(
'first_name' => $request->firstName,
'surname' => $request->lastName,
'phone' => $request->phone,
'email' => $request->email,
'gender' => $request->gender,
'parent_id' => $parentID
'password' => Hash::make($request->firstName)
);
Student::create($data);
return back()->with('success', 'Student successfully added.');
pluck returns Enumerable, you need the actual value, try:
$parentID = $parentt->id;
We can use the pluck() method when there are a collection of objects but in your case, the query returns one object, hence you can directly call the id as #Script47 mentioned.
$parentID = $parentt->id;

How make a register form codeigniter with different database table

I tried to make a register form on a multiuser website with a different database table.
Eg when user1 registers, the data will be entered in table "user1",
when user2 registers, entered in table "user2".
I can only enter user1 and user2 into the same table.
This is my code using role_id
$data = [
'name' => htmlspecialchars($this->input->post('nama', true)),
'username' => htmlspecialchars($this->input->post('username', true)),
'photo' => 'default.jpg',
'password' => password_hash($this->input->post('password1'), PASSWORD_DEFAULT),
'role_id' => 2,
'is_active' => 1,
'is_date' => time()
];
You can do this by applying condition on role_id but this is only possible if there are only a number of users. If there are many users and you want to make a separate table for each one of them, try Database Forge Class(Bad practice)
I've written a possible solution for your question, comments are mentioned wherever necessary. See if it helps you.
Controller
$data = [
'name' => htmlspecialchars($this->input->post('nama', true)),
'username' => htmlspecialchars($this->input->post('username', true)),
'photo' => 'default.jpg',
'password' => password_hash($this->input->post('password1'), PASSWORD_DEFAULT),
'role_id' => 2,
'is_active' => 1,
'is_date' => time()
];
$this->xyz_model->xyz_function($data); // load xyz_model and call xyz_function with $data parameters
Xyz_model
function xyz_function($data){
$table = 'user1'; // default value
if($data['role_id'] != 1){ // other value is 2 -- assuming only 2 users are there(if not user if else or switch)
$table = 'user2';
}
$this->db->insert($table, $data);
return $this->db->insert_id();
}

Insert into two tables in Laravel

I have a register form, in that form user can select whether they are Farmer or Buyer from a dropdown list. If the user select Farmer then I want to add the newly created user_id to the farmer table. If the user select Buyer then I want to add the newly created user_id to the buyer table.
But the behaviour now is when the user select Buyer from the dropdown list. The newly created user_id is saved on the farmer table instead of the buyer table.
How do I save the newly created user_id to the corresponding table?
Below are my code:
$user = User::create([
'username' => $data['username'],
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
'group' => $data['group'],
]);
$farmer = Farmer::make([
'user_id' => $user->id,
]);
$user->farmer()->save($farmer);
return $user;
do like this.
$decide = $data['select_option'];
if($decide == 'farmer'){
$farmer = Farmer::create([
'user_id' => $user->id,
]);
}
elseif($decide == 'buyer'){
$buyer = Buyer::create([
'user_id' => $user->id,
]);
}
I think you have a couple issues:
First, you are not using the check you described;
there is select form that decide if user is farmer or buyer
Second, you are just creating a farmer, nothing to do with the buyer you described
if the user is buyer, then buyer table get his/her user_id
Solution, is you need to first utilize the check, then create those table entries appropriately.
Also, please wrap your code in a transaction:
DB::transaction(function(){
// Your code here...
})
Thank you guys for help me, I found the easiest way to solve my issues with this below :
if ($user->group == 2) {
$buyer = Buyer::create([
'user_id' => $user->id,
]);
}elseif ($user->group == 3) {
$farmer= Farmer::create([
'user_id' => $user->id,
]);
}
$user->save();
return $user;

Update by referring foreign key

Password already been exist in Passw Model/Table. Here i want to change my password.
I want to update using regist_id(foreign key), not by Id in table passw.
Controller:
$passw = Passw::whereRegist_id($id)->get(); //Regist_id is an foregin key
$regist->pass()->update([
'password1' => $request->newpassword,
'password2' => $request->newpassword1
]);
return view('welcome');
Regist Model:
public function pass(){
return $this->hasOne('App\Passw');
}
When i give update it redirect to welcome page. But not password value been changed.
Where am i do mistake.
You can update it like this
$passw = Passw::where('regist_id', $id)->first();
$passw->update([
'password1' => $request->newpassword,
'password2' => $request->newpassword1
]);
You can fetch Regist model using $id
$regist = Regist::with('pass')->find($id);
$regist->pass->update([
'password1' => $request->newpassword,
'password2' => $request->newpassword1
]);

Will Model::updateOrCreate() update a soft-deleted model if the criteria matches?

Let's say I have a model that was soft-deleted and have the following scenario:
// EXISTING soft-deleted Model's properties
$model = [
'id' => 50,
'app_id' => 132435,
'name' => 'Joe Original',
'deleted_at' => '2015-01-01 00:00:00'
];
// Some new properties
$properties = [
'app_id' => 132435,
'name' => 'Joe Updated',
];
Model::updateOrCreate(
['app_id' => $properties['app_id']],
$properties
);
Is Joe Original now Joe Updated?
OR is there a deleted record and a new Joe Updated record?
$variable = YourModel::withTrashed()->updateOrCreate(
['whereAttributes' => $attributes1, 'anotherWhereAttributes' => $attributes2],
[
'createAttributes' => $attributes1,
'createAttributes' => $attributes2,
'createAttributes' => $attributes3,
'deleted_at' => null,
]
);
create a new OR update an exsiting that was soft deleted AND reset the softDelete to NULL
updateOrCreate will look for model with deleted_at equal to NULL so it won't find a soft-deleted model. However, because it won't find it will try to create a new one resulting in duplicates, which is probably not what you need.
BTW, you have an error in your code. Model::updateOrCreate takes array as first argument.
RoleUser::onlyTrashed()->updateOrCreate(
[
'role_id' => $roleId,
'user_id' => $user->id
],
[
'deleted_at' => NULL,
'updated_at' => new \DateTime()
])->restore();
Like this you create a new OR update an exsiting that was soft deleted AND reset the softDelete to NULL
Model::withTrashed()->updateOrCreate([
'foo' => $foo,
'bar' => $bar
], [
'baz' => $baz,
'deleted_at' => NULL
]);
Works as expected (Laravel 5.7) - updates an existing record and "undeletes" it.
I tested the solution by #mathieu-dierckxwith Laravel 5.3 and MySql
If the model to update has no changes (i.e. you are trying to update with the same old values) the updateOrCreate method returns null and the restore() gives a Illegal offset type in isset or empty
I got it working by adding withTrashed so that it will include soft-deleted items when it tries to update or create. Make sure deleted_at is in the fillable array of your model.
$model = UserRole::withTrashed()->updateOrCreate([
'creator_id' => $creator->id,
'user_id' => $user->id,
'role_id' => $role->id,
],[
'deleted_at' => NULL
])->fresh();
try this logic..
foreach ($harga as $key => $value) {
$flight = salesprice::updateOrCreate(
['customerID' => $value['customerID'],'productID' => $value['productID'], 'productCode' => $value['productCode']],
['price' => $value['price']]
);
}
it work for me

Resources