How make a register form codeigniter with different database table - codeigniter

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

Related

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;

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

Avoid duplication in doctor_id field with where clause in laravel 5.4

this is my doctors id
this is my user id
I can't insert anything when I put unique in the validation of doctor_id. When there's no unique it works fine.
I want to avoid duplicate doctor_id where auth::id == 1. Any advice is appreciated.
public function store(Request $request, $id)
{
$auth = Auth::id();
$constraints = [
'doctor_id' => 'required|unique',
'day1' => 'required|max:20',
'day2'=> 'required|max:60',
'day3' => 'required|max:60'
];
$input = [
'users_id' => $auth,
'doctor_id' => $id,
'day1' => $request['day1'],
'day2' => $request['day2'],
'day3' => $request['day3'],
'day4' => $request['day4'],
...
'day27' => $request['day27'],
'status' => '1'
];
$this->validate($request, $constraints);
Itinerary::create($input);
$added = array('added'=> 'Added Doctor to Itinerary Successful!!');
return redirect()->back()->with($added);
Have you tried this? (assuming your table is named itineraries):
'doctor_id' => 'unique:itineraries'
According to Laravel Doc, you should add the table name, and column name if possible:
unique:table,column,except,idColumn

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

authorisation based on values not on verb

I'm implementing an authorisation process based on values not on verb.
Example:
all users/groups are allowed to update a db field
admin can set status to all possible values (confirmed | pending | cancelled)
supplier can set to 'confirmed'
All examples I find go around a user/group being able or not to insert,update or delete something.
Is there something out there to deal with situations like this out of the box, or this has be hard coded?
Basically what you need is something hard to maintain in any application: granular permissions.
You can get this to work easily using Cartalyst's Sentry. Here's how I do it:
All my routes are hierarchically organized and named as such:
<?php
Route::get('login', array('as'=>'logon.login', 'uses'=>'LogonController#login'));
Route::get('logged/out', array('as'=>'logon.loggedOut', 'uses'=>'LogonController#loggedOut'));
Route::group(array('before' => 'auth'), function()
{
Route::get('logout', array('as'=>'logon.logout', 'uses'=>'LogonController#logout'));
Route::group(array('before' => 'permissions'), function()
{
Route::get('store/checkout/shipping/address', array('as'=>'store.checkout.shipping.address', 'uses'=>'StoreController#shippingAddress'));
Route::get('store/checkout/payment/confirmed', array('as'=>'store.checkout.payment.confirmed', 'uses'=>'StoreController#confirmed'));
Route::get('profile', array('as'=>'profile.show', 'uses'=>'ProfileController#show'));
});
});
Those under the filter 'permissions' are subject to check if user has rights to use them:
Route::filter('permissions', function()
{
$name = Route::current()->getName();
$name = 'system' . ( ! empty($name) ? '.' : '') . $name;
if (!Permission::has($name)) {
App::abort(401, 'You are not authorized to access route '.$name);
}
});
Basically here I get the current route name, add 'system.' to it and check if the user has this particular permission.
Here's how I create my groups and populate permissions:
<?php
public function seedPermissions()
{
DB::table('groups')->truncate();
$id = 1;
Sentry::getGroupProvider()->create(array(
'id' => $id++,
'name' => 'Super Administrators',
'permissions' => array(
'system' => 1,
),
));
Sentry::getGroupProvider()->create(array(
'id' => $id++,
'name' => 'Administrators',
'permissions' => array(
'system.users' => 1,
'system.products' => 1,
'system.store' => 1,
'system.profile' => 1,
),
));
Sentry::getGroupProvider()->create(array(
'id' => $id++,
'name' => 'Managers',
'permissions' => array(
'system.products' => 1,
'system.store' => 1,
'system.profile' => 1,
),
));
Sentry::getGroupProvider()->create(array(
'id' => $id++,
'name' => 'Users',
'permissions' => array(
'system.store.checkout' => 1,
'system.profile' => 1,
),
));
}
So if a user is trying to add some shipping address, the route 'store.checkout.payment.confirmed', as every user has access to 'system.store.checkout', everything inside that route will available to him.
And this is how I check for permissions:
public static function has($permission)
{
$all = [];
$parts = explode('.',$permission);
$permission = '';
foreach($parts as $part) {
$permission .= (!empty($permission) ? '.' : '') . $part;
$all[] = $permission;
}
return Sentry::check() and Sentry::getUser()->hasAnyAccess($all);
}
It basically builds a list of routes:
system
system.store
system.store.checkout
system.store.checkout.payment
system.store.checkout.payment.confirmed
And if Sentry finds one of those in the users granular permissions it will return true.
Now I just have to add users to groups:
Sentry::findUserById(1)->addGroup( Sentry::getGroupProvider()->findByName('Users') );
And if I need to go granular on a particular user/permission I just need to:
$user = Sentry::findUserById(1);
$user->permissions['store.checkout.payment'] = false;
$user->save();
And the user will never be able to pay for anything in the store again. :)

Resources