After registration i need to redirect to user dashboard directly. I need to set session based on user role and last registered id. how to set this. already i have setsession function auth_model.php based on this i need to setsesion
function setUserSession($row=NULL)
{
switch($row->role_name)
{
case 'owner':
$values = array('user_id'=>$row->id,'logged_in'=>TRUE,'role'=>'owner');
$this->session->set_userdata($values);
break;
case 'employee':
$values = array('user_id'=>$row->id,'logged_in'=>TRUE,'role'=>'employee');
$this->session->set_userdata($values);
break;
}
}
i am doing registration using ajax and redirect using windows.location.href= "dashboard.php"
we need to setsession when we get the success status in php file. we need to set the session
$this->session->userdata('last_generated_id')
select * from users where user_id = $this->session->userdata('last_generated_id')
$row = $this->db->result();
$this->auth_model->setUserSession($row);
redirect('logged_in_page');
Related
So I have a License model created through the octoberCMS builder with the List and Form views.
The license model contains one relation to School model.
Under the Form view there is a dropdown list with schools and an input field (type=number) which defines how many Licenses to create for the chosen school.
The default behaviour creates only 1 license
How to create the entered amount of licenses instead?
You need to override default behaviour.
Note: This task require programming knowledge of OctoberCMS.
In your controller you need to add this method.
use Flash;
use Backend;
// ...
public function create_onSave($context = null)
{
// 1. init form for your modal and get input data from it
$model = $this->asExtension('FormController')->formCreateModelObject();
$model = $this->asExtension('FormController')->formExtendModel($model) ?: $model;
$this->asExtension('FormController')->initForm($model);
$form = $this->asExtension('FormController')->formGetWidget();
$data = $form->getSaveData();
// 2. get proper count field here and convert to int for loop
$count = intval($data['license_to_create']);
// 3. validation step
// if($validationFailed) {
// Flash::error('Something Went Wrong.');
// return;
// }
// 4. loop
foreach ($i = 1; $i <= $count; $i++) {
$licenseModel = new LicenseModel;
// you can add other data
// you can access $data['school_id'] here
// $licenseModel->school_id = $data['school_id'];
$licenseModel->save();
}
// 5. success message
Flash::success($count . ' License Added');
// 6. just redirect it to desired location
return Backend::redirect('/hardiksatasiya/sotest/skills');
}
Explanation
here we initialise required variables so we can get data which were filled in text box, this is default code so i just copied it from core code.
once we have our $data variable we can access filled data we use $data['license_to_create'] in your case its 100, and $data['school_id'] for which school you need to create license,
Note: you may have different fields please change accordingly.
validation step *optional, you can add some checks here and stop flow if something is not correct with error message.
loop to create new records for license modal ,[ default code will create only 1 record], but here we create it based on given count $data['license_to_create']
just normal success message.
redirect where we need to redirect normally you need to redirect it to /author-name/plugin-name/license-controller Note: you may have different url please change accordingly.
please add comment if you have any doubt.
Well actually I solved it already also by writing a custom create_onSave function for Licenses controller:
public function create_onSave(){
$quantity = post('License[_quantity]');
$school_id = post('License[school]');
for($i = 1; $i <= $quantity; $i++){
# Create License
$license = new \Acme\Plugin\Models\License();
$license->school_id = $school_id;
$license->save();
}
\Flash::success('Added '.$quantity.' Licenses');
}
I am creating a REST server and would like to create a url like so
DELETE /companies/3/employees/45
The endpoint should delete employee 45, which belongs to company 3.
How exactly would i go about creating a above URL using codeigniter.
Try the following:
In your routes.php add a new route:
$route['companies/(:num)/employees/(:num)'] = 'companies/employees/$1/$2';
Where companies is the controller and employees is the action.
and in your controller, write action something like:
//Use some kind of input validations for the Ids
public function employees($companyId = 0, $employeeId = 0)
{
if(strtolower($_SERVER['REQUEST_METHOD']) == 'delete')
{
//delete query here
}
}
This uses CI routing to get params, and uses superglobal $_SERVER to determine whether the Request Method being used for the call is DELETE.
first you need to make a rest app like this link
Then you can make a route like
$route["companies"]["delete"] = 'company/delete';
In your controller company
function delete ( ) {
foreach($this->input->post() as $item => $value){
${$item} = $value;//making variables $employee_id, $company_id
}
//logic to delete
}
You need to send that info by post or make almost the same sending it to get
I'm currently developing an MLM Website using Codeigniter Framework.
And I am working on registration now. I can register successful with referral user
The problem is every 3 registration using my referral username/id i need to run another query because in 1st and 2nd referral I earned 200. and in 3rd user will refer i will only earn 100.
How can I do that in Codeigniter? anyone done this? please help
Let me throw some light on this
So lets say you make a post for every registration, the post goes to a class names registration and a register method, and the referral id runs as a session (refID). Also, you have a registration model, this is what you should likely do:
class registration extends CI_Controller{
function __construct(){
parent::__construct();
$this->load->model('registration_model');
}
//ensue to check for the existence of the refID session before processing
function register(){
if($_POST){
//first run form validation
//you should have auto loaded the form_validation library
//and created a rules function that carries the form rules
$rules = $this->rules();
$this->form_validation->set_rules($rules);
if($this->form_validation->run() == FALSE){
//load view here
}else{
//first, get post data
//then get the number of registration done by user using the refID
//if registration is greater than 2, set earnings to 100
//set earnings to 200
//then proceed to insert registration and do something else
//get post data, assumed post data
$name = $this->input->post('name');
$email = $this->input->post('email');
//get number of registrations
$numOfRegs = $this->registration_model->getRegByRefID();
//set the earnings from the number of registrations
$earning = $numOfRegs < 3 ? 200 : 100;
//please note that the for $numOfRegs = 4, $earnings will be 100, as this was not specified in the question
//at this point, you have set the earnings, you can proceed to do whatever you wish to do, perhaps insert the records
//please note that this code block just explains what you can likely do after setting the earnings
$insert = array(
"name" => $name,
"email" => $email,
"earning" => $earning
);
$this->registration_model->insert($array);
// then do anything else
}
}else{
//load view here
}
}
}
Now this is how your registration model will look like this
class Registration_model extends CI_Model{
function __construct(){
parent::__construct();
}
function getRegByRefID(){
$refID = $this->session->refID;
return $this->db->get_where('mydb', array("refID" => $refID))->num_rows();
}
}
I hope this explains what you really wants, and helps you. If you find any difficulty, kindly comment and lets sort it out.
I am writing the following code to logout particular user from Admin System.
I have session table. I am following this link : https://laravel.com/docs/5.2/session
$User = $this->Get($obj);
$UserSession = SessionModel::where('user_id', $obj->UserID)->first();
if($UserSession != null) {
$UserSession->user_id = null;
$UserSession->payload = null;
$UserSession->save();
}
Is it a correct approach to do so?
You can really clean this up in one line of code:
$deleted = SessionModel::whereUserId($obj->UserID)->delete();
// Returns the number of deleted sessions.
return $deleted;
Deleting all session records that belong to a user will log the user out of all sessions they have.
For example, if a user is logged in on your application on their phone and computer, they will be logged out on both devices.
$User = $this->Get($obj);
$UserSession = SessionModel::where('user_id', $obj->UserID)->first();
if($UserSession != null) {
$UserSession->user_id = null;
$UserSession->payload = null;
$UserSession->save();
}
You must noticed that is user can have more session records if user logs in with many different browser
=> Solution: get all rows with given user_id in sessions table and delete them. Use useful Collection method
$User = $this->Get($obj);
// Get Collection Object
$UserSessions = SessionModel::where('user_id', $obj->UserID)->get();
if($UserSession != null) {
// Use each method on Collection Object
$UserSessions->each(function($UserSession){
$UserSession->delete();
});
}
You might consider that the user_id in your Session table should be nullable and have a default null value, since users that are not logged in have no user id. Then your migration might have this line.
$table->integer('user_id')->unsigned()->nullable()->default(null);
Then deleting the row of a specific user in this table would delete that users session.
In my web application using codeigniter, I stored role data that I have query from database before in session.
$role = $this->session->userdata('role');
And in every model or controller, i always use this variabel ($role) to manage user behaviour in my web.
Such as
if($role==1)
{
//Behaviour for admin.
}
else if($role==2)
{
//Behaviour for general user
}
else
{
//Do something
}
My problem : If many users login to my system, the session data always lost without click logout before. Thanks.
FOR YOUR INFORMATION :
I have store the role in database, but for easy way the value of role that i've get before, I stored it in session. FOr the easy solution. Thanks.
Store the role in the database in a users table. I have 4 roles in my application student, staff, admin, president.
You then would query the database on the username that was entered,
if the role = 1 then send to the appropriate page.
Sort of like this :
$sql = "SELECT * FROM users WHERE username = :username AND role = 1";
$role = $this->db->conn_id->prepare($sql);
$role->bindParam(':username', $username);
$role->execute();
if ($role) {
if ($role->rowCount() == 1) {
return TRUE;
}
}
then in the controller do
if ($this->yourmodel->yourfunction($yourvariable)) { // Checks if the query above returns TRUE!
redirect(to what ever page you want)
}