Insert into two tables in Laravel - 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;

Related

Add the inserted id to the pivot table

I have a users, items, user_item tables. I need to populate the user_item table with a user_id and item_id when a user is created.
so far, I have a basic registration function
public function register(Request $request) {
$user = User::create([
'name' => $request->name,
'user_type' => $request->user_type,
'email' => $request->email,
'password' => bcrypt($request->password)
]);
$token = auth()->login($user);
return $this->respondWithToken($token);
}
So far it saves only to the users table ofcourse.
I've looked at some documentations on using attach(), however, I got stuck on this one..
In the register function, i added a $item array:
$item = Item::create([
'user_id' => !!!!, -> How do I get the id of the inserted user
'instrument_id' => $request->instrument_id
]);
$user->role()->attach($item)
Also, what is role()? is it a built-in laravel function?
Note that I haven't tried running this function since I got stuck on these problems. So I don't event know if it's gonna work.
Anyone help me on this one? I'm a laravel newbie and got really confused on the documentations.
the method create return the model it self after loading it's attributes from db,
so when you want the user id just use $user->id after create() method.
for the default permission that shipped with laravel it is
spatie/laravel-permission
and to assign role to a user you can use:
$user->assignRole('writer'); // just set role name

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();
}

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
]);

How to associate from a parent model to another

$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

correct value instead of array

scenario is crm with tables account, account_contact, contact and account_contact_role. The latter contains roles like 'project lead' or 'account manager' for the combos defined in the junction table.
My challenge is the account view, that is listing also the connected persons with their roles. I want my grid to show: Doe | John | employee.
The problem is now when the contact has 2+ entries in the junction table. How can I print the correct role for the row? As you can see in the code I solved it the static way which shows only 1 out of n times the correct value. Tried it with inner join without success. Is it a problem of the search in the model or with the access in the view?
the relation from the account model to the contacts:
public function getContacts($role = null)
{
// many-to-many
return $this->hasMany(ContactRecord::className(), ['id' => 'contact_id'])
->via('accountContacts')
->innerJoinWith(['accountContacts.role'])
->andWhere(['account_contact.account_id' => $this->id])
->andWhere(['account_contact_role.type' => $role])
;
}
the view
<?= \yii\grid\GridView::widget([
'dataProvider' => new \yii\data\ActiveDataProvider([
'query' => $model->getContacts('internal'),
'pagination' => false
]),
'columns' => [
'lastname',
'firstname',
[
'label' => 'Role',
'attribute' => 'accountContacts.0.role.name',
],
[
'class' => \yii\grid\ActionColumn::className(),
'controller' => 'contacts',
'header' => Html::a('<i class="glyphicon glyphicon-plus"></i> Add New', ['contact-records/create', 'account_id' => $model->id]),
'template' => '{update}{delete}',
]
]
]); ?>
defined relations are:
account has many accountContacts has one contact
accountContacts has one accountContactRole
Many thanks in advance!
You are showing account's contacts, so you have to list from Contact model.
Inside Contact model (or Contact ActiveQuery file):
public static function queryContactsFromAccountAndRole($account, $role = null)
{
// many-to-many
return ContactRecord::find()->innerJoinWith(['accountContacts' => function($q) use($account, $role) {
$q->innerJoinWith(['accountContactsRole'])
->andWhere(['account_contact.account_id' => $account->id])
->andWhere(['account_contact_role.type' => $role]);
}])
->andWhere(['account_contact.account_id' => $account->id]);
}
Now you have one record for each contact and the gridview will show all contacts.

Resources