I need to get the user id of the person logged in, so that i can run a query for that user. Im using ion auth, should i use a session or call it from the db, should i use a helper or not? anyway, heres what im trying to do:
example: how many work orders does logged in user have?
query would be: select * from work_orders WHERE status = "1" AND userid = "%THE LOGGED IN USER"
here is my controller, which doesnt have the "get user id" code:
public function index()
{
$this->load->view('templates/header');
$data['total_open_wo'] = $this->Home_model->total_open_wo();
$data['result'] = $this->Home_model->index();
$this->load->view('home', $data);
$this->load->view('templates/footer');
}
here is my model:
public function total_open_wo() {
$this->db->where('status', "1");
$this->db->where('tid', "NEED_THE_USER_ID");
$num = $this->db->count_all_results('work_orders');
return ($num);
}
Provided the user is logged in you can get the user ID by using the get_user_id() function in ion auth. On a related note in your model you need a $this->db->from() call to set the table to fetch the number of rows from.
public function total_open_wo() {
$userId = $this->ion_auth->get_user_id();
$this->db->where('status', '1');
$this->db->where('tid', $userId);
$this->db->from('work_orders');
$num = $this->db->count_all_results();
return $num;
}
Use the function $this->ion_auth->logged_in() to make sure that the user is logged in before calling the model function.
you can retrieve the logged in user details using user() method.
For example to get user id
echo $this->ion_auth->user()->row()->id;
Related
I have users with role manager, and I only want them to update or view other users(employee) data that belong in the same department as the manager user. If the manager user is not in the same department as the user he's trying to update it should redirect the back.
i.e., the manager might try to change the user id in the URL, and I want to deny access to if that user belongs in another department.
I have all my roles and permissions set up.
The Department field is in USER TABLE
public function show($id)
{
$team = User::where('id', $id)->with('roles')->first();
return view('backend.user.team.show', compact('team'));
}
public function edit($id)
{
$user_roles = Role::all();
$team = User::find($id);
$business = Business::all();
return view('backend.user.team.edit', compact('team', 'user_roles', 'business'))->with('user', auth()->user());
}
You should use policies and gates.
Take a look at the documentation:
Writing policies
Writing gates
Basically, you should do something like this:
Create a policy to handle your user permissions:
php artisan make:policy UsersPolicy
This command will create a UsersPolicy file within the App/policies/ directory.
Open the UsersPolicy file and create a checkUserDepartament within that file:
public function checkUserDepartament(User $user, User $userToBeManaged)
{
return $user->departament === $userToBeManaged->departament;
}
The function above return true if the current logged in user departament is the same of the user you want to edit. Otherwise, return false.
Within your AuthServiceProvide:
Gate::define('user-belongs-to-same-departament', 'App\Policies\UsersPolicy#checkUserDepartament');
To use the Gate, do something like this within your controller:
use Gate; //At the top of the controller.
// I assume that $id is the id of the user you want to edit.
public function edit($id)
{
if(Gate::allows('user-belongs-to-same-departament', User::find($id))){
$user_roles = Role::all();
$team = User::find($id);
$business = Business::all();
return view('backend.user.team.edit', compact('team', 'user_roles', 'business'))->with('user', auth()->user());
}else {
return response('Unauthorized', 401);
}
}
Hope it helps.
With Codeigniter session.
I have created the ci_session table.
In this table I save session datas in the blob datatype.
$sess_data= array(
'logged_in' => TRUE
);
$this->session->set_userdata($sess_data);
For count all online users, I need to get logged_in==1 value in blob datatype.
For example, user 1 is logged in with Chrome web browser. User2 is logged in with Mozilla. In the database there are 2 sessions with the different session id.
How can i get this all logged_in==1 values in this ci_session table?
This is my model function.
Please help me the fill where place in this function?
public function count_online_users(){
$this->db->select('*');
$this->db->from('ci_session');
$this->db->where(...........);
$query = $this->db->get()->num_rows();
return $query;
}
Check this this method you have to follow
First you have to update logged_in = 1 in your users table as your defined name
after you get number of users are logged_in
// Update user in to call this function
$data = array(
'logged_in' => '1'
);
public function update_user($user_id, $data)
{
$this->db->where('id',$user_id);
$this->db->update('users',$data);
}
// After you get logged in user in total value
public function count_online_users()
{
$this->db->select('*');
$this->db->from('users');
$this->db->where('logged_in','1');
$query = $this->db->get()->num_rows();
return $query;
}
You can use javascript and asynchron request for update field. When you close the window, the handler of window.onunload is called
var unloadHandler = function(e){
//here ajax request to close session
};
window.unload = unloadHandler;
To solve the problem of redirection, php side you can use a counter
class someController extends Controller {
public function methodWithRedirection(){
$this->session->set_userdata('isRedirection', 1);
//here you can redirect
}
}
class homeController extends Controller{
public function closeConnection(){
$this->load->library('session');
if($this->session->userdata('isRedirection')!== 1){
//destroy session
}
}
}
Top of my controller i have added:
use Auth;
function in my controller
public function details($id)
{
if(Auth::check())
{
$user = Auth::user();
$product = Product::find($id);
$cart->product_id = $product->id;
$cart->category_id = $product->category_id;
$cart->user_id = $user->id;
dd($cart->user_id); //check if its storing the value
}
else {
return redirect()->route('login');
}
}
when I run this i get error:
Creating default object from empty value
If I remove the $user->id line the error goes.
I tried adding constructor also but still got same error
public function __construct() {
$this->middleware('auth');
}
dd is showing other details after it checks if user is logged in.
Is there a way to get user id of logged in user from users table that is created by default.
Thanks!
The issue is you’re calling $cart->product_id, but the $cart variable isn’t defined as far as I can see. PHP doesn’t know what to do, so because you try and assign a property to it, PHP assumes you want $cart to be a class, hence the “Creating default object from empty value” message.
Other than that, you code could be improved by using middleware to authenticate your users, and relations on your Eloquent models so you’re not manually assigning relation IDs.
Try like this,
You forgot to initials cart object
$cart = new Cart;
$cart->product_id = $product->id;
$cart->category_id = $product->category_id;
$cart->user_id = $user->id;
dd($cart->user_id); //check if its storing the value
After I created a registration form with the fields: user, email, pass, cpass, I saved the user field in a session, so when I submit the form it should redirect me to the homepage displaying the message: hello + $this->session->userdata('user').
In my login form I have only the fields: email, pass and I want after submitting the form to be redirected aswell to my homepage displaying the same message but I don't know how to save the username in the session.How can I do that?
suppose you have a function in your model claass for checking user credentials.like-
function check_user($email, $pass) {
//select db column that you will need for future task
$this->db->select('id, user, email, pass);
$this->db->from('user_table');
$this->db->where('email', $email);
$this->db->where('pass', $pass);
$this->db->limit(1);
$query = $this->db->get();
if ($query->num_rows() == 1) {
return $query->result();
} else {
return false;
}
}
after returning in your controller function just put them in the session.like-
public function do_login(){
$result = $this->login_model->check_user($email, $pass);
//put them in the session
foreach($result as $row){
$this->session->set_userdata('user_id', $row->id);
$this->session->set_userdata('user', $row->user);
$this->session->set_userdata('email', $row->email);
//put more information as your need
}
}
please modify the code as your situation.
I'm trying to display a profile View depending if a user has activated their account - i.e. active = 1 (or 0 for inactive)
If the user has activated their account show a View with users details of if they haven't display a different View saying they need to activate their account.
This is the code I am having trouble with:
public function user($username) {
// Get the /username from URL and check the database
$user = User::where('username', '=', $username);
// If /username does exist
if($user->count()->('active', '=', 1)) {
// Grab user info from database
$user = $user->first();
// return the active user view
return View::make('profile.active-user')->with('user', $user);
} else {
// Grab user info from database
$user = $user->first();
// return the inactive view
return View::make('profile.inactive-user')->with('user', $user);
}
return App::abort(404); // else throw a 404
}
Any help/logic would be really appreciated.
Thanks, Jack.
You can simplify it a bit by combining the eloquent query and 404. Also you already have your user object after the query so no need for extra eloquent stuff:
public function user($username) {
//get user from db, if no result throw not found (404)
$user = User::where('username', '=', $username)->firstOrFail();
if($user->active) {
// return the active user view
return View::make('profile.active-user')->with('user', $user);
} else {
// return the inactive view
return View::make('profile.inactive-user')->with('user', $user);
}
}