to check authenticated user and handle session time - laravel

I have this mechanism of checking the logged-in user role in a blade page so that I can give him/ her the selected pages but I find after a user has logged in and stayed idle for a long time and when he is back and wants to continue in the page he is getting an error
ErrorException
Trying to get property 'id' of non-object (View: /var/www/html/poss_v1/resources/views/dashboard/student/index.blade.php)
and my code is here below
<?PHP
$user = Auth::user();
$user_id = $user->id; //----here is the problem it is missing the id when the session has ended--//
$role_user = App\Models\RoleUser::where('user_id', $user_id)->first();
$role_name = App\Models\Role::where('id', $role_user->role_id)->first();
$role = $role_name->name;
?>

#php
if(Auth::check()){
$role_user_id = App\Models\RoleUser::where('user_id', auth()->id())->first()->role_id;
$role = App\Models\Role::where('id', $role_user_id)->first()->name;
}
#endphp

In Laravel blade file you should check logged in user in this way.
#php
if(Auth::check()){
$user = Auth::user();
$user_id = $user->id;
$role_user = App\Models\RoleUser::where('user_id', $user_id)->first();
$role_name = App\Models\Role::where('id', $role_user->role_id)->first();
$role = $role_name->name;
}
#endphp

To increase the lifetime of your session, you may modify the env variable SESSION_LIFETIME to whatever minutes you wish.
And to make sure your user doesn't get this error, you may check if the session is still alive with Auth::check()

Related

Welcome email with create password link in laravel7

I'm creating an one form where the admin register the new users and then an email is sent to this new user with a welcome message and a link to create a new password.
This last part I'm having problems as I can't find info on how to generate the token and the link.
This link should redirect the user to a create password page, which is different than the reset password.
Thanks !
Below is my add user controller:
public function contactSave(Request $request)
{
$token = $request->_token;
$user= new User;
$user->name = $request->name;
$user->email = $request->email;
$user->password = $password;
$user->save();
if($user->id)
{
$CustomerContact= new CustomerContact;
// $CustomerContact->name = $request->name;
// $CustomerContact->email = $request->email;
$CustomerContact->phone = $request->phone;
$CustomerContact->address = $request->address;
$CustomerContact->user_id = $user->id;
$CustomerContact->country_id = $request->country;
$CustomerContact->state_id = $request->state;
$CustomerContact->comment = $request->comment;
$CustomerContact->organization = $request->organization;
$CustomerContact->captcha = $request->captcha;
$CustomerContact->save();
$details = [
'title' => 'Hi '.$request->name.'',
'body' => 'Your account has been created successfully. Request you set your password with this link',
// 'link' => URL::route('password/reset/'.$token)
];
\Mail::to($request->email)->send(new \App\Mail\ContactMail($details));
}
return redirect('contacts')->with('success', 'User created successfully.');
}
Current I am just sending mail to user mail id. I am not getting how to send password reset (password set link) url into that mail.
On that link click forgeot password form open and user can reset there passowrd.
Anyone idea then let me know.

Can't get id from Auth::check

I try to get user id in the Laravel app. In my User.php I added this code
if (Auth::check())
{
$id = Auth::id();
echo '<script>console.log($id)</script>';
}
I get below given error:-
Uncaught ReferenceError: $id is not defined
What am I doing wrong?
You are mingling the logic of JS and PHP :)))
if (Auth::check())
{
$id = Auth::id();
echo '<script>console.log('.$id.')</script>';
}
OR simply echo it?
if (Auth::check())
{
$id = Auth::id();
echo $id;
}
OR you could use a double quote if you really wanna print it under script tags with your current format:
if (Auth::check())
{
$id = Auth::id();
echo "<script>console.log($id)</script>";
}
Access Id like this:
$id = Auth::user()->id;

How can I pass username in controller?

Username is store in my session. I am working on leave management module.
My Leave module's table has these fields
User Name, Leave Type, Duration, Status, & Action.
Apart from username all details I can insert and list in list view.
But my user name is store in session.
How can i get it from session and store in database In Username field??
Code in my view file
#if(Session::has('key'))
<?php $username = Session::get('key')['username']; ?>
#endif
<input type="hidden" name="username" value="<?php echo $username ?>">
Code In My controller file
public function leaveApplication(Request $request)
{
$leave = new LeaveManagement();
$leave->username = $request->get('username');
$leave->leaveType = $request->get('leaveType');
$leave->startDate = $request->get('startDate');
$leave->endDate = $request->get('endDate');
$leave->fromLeave = $request->get('fromLeave');
$leave->fromHalfDayLeaveType = $request->get('fromHalfDayLeaveType');
$leave->toLeave = $request->get('toLeave');
$leave->toHalfDayLeaveType = $request->get('toHalfDayLeaveType');
$leave->fullDayLeave = $request->get('fullDayLeave');
$leave->typeOfLeave = $request->get('typeOfLeave');
$leave->reasonForLeave =$request->get('reasonForLeave');
$leave->status = 'Pending';
$leave->save();
return redirect('leave');
}
You can use Laravel global session helper: session(keyName).
To get username from session and store it in database:
$username = session('username');
$leave = new Leave();
$leave->username = $username;
$leave->save();
For more information on Laravel session see Laravel Session
you can get object from your session and access to its attributes.some thing like:
$user = session()->get('user')
$username = $user->username
or after logging you can access your user's username with:
auth()->user()->username
After login, Auth maintains user table fields in it. You can access it like that -
echo Auth::user()->name or echo Auth::user()->email
It will return the expected values as : "usersname" and "useremail#domain.com".
If you are not using Auth, then you can get username from your session and save it in DB like that -
$user = session()->get('user')
$username = $user->username;
$leave = new LeaveManagement();
$leave->username = $username;
$leave->save();
Hope this will help you.

Joomla 2.5+: Creating an Account and Log in within the same Controller Call

I have created a from with a user registration. When processing the form within the controller, I want the user to be logged in afterwards. Account creation works fine, but logging right afterwards fails:
function processForm($username,$first_name,$last_name,$email,$password,$groups) {
jimport('joomla.user.helper');
$app = JFactory::getApplication('site');
$user = new JUser();
$b= array();
$user->bind($b);
$user->username = $username;
$user->name = $first_name." ".$last_name;
$user->set('id',0);
$date =date("Y-m-d H:i:s");
$user->set('registerDate', $date);
$user->email = $email;
$user->set('password',JUserHelper::getCryptedPassword($password,JUserHelper::getSalt()));
$user->set('block', '0');
$user->save();
foreach ($groups as $group) {
JUserHelper::addUserToGroup($user->id, $group);
}
$app->login(array("username"=>$username,"password"=>$password));
}
Any idea?

Laravel 4: Updating a user

I'm trying to update the password of a user I've pulled from the database in Laravel 4. Here is what I have:
$user = User::where('username', $username)->get();
if (!empty($user)) {
$user->password = Hash::make($password);
$user->save();
}
But Laravel is telling me save is an unknown method. What am I doing wrong here?
get returns an array of users. You need to use first to get a single user object that will allow you to adjust the password and save the record.
if ($user = User::where('username', $username)->first())
{
$user->password = Hash::make($password);
$user->save();
}
Are you sure $user actually has a 'user' in it?
It wont be 'empty' - it will be BOOL false. Try var_dump($user) and confirm something is returned?
Try this:
$user = User::where('username', $username)->get();
var_dump($user);
if ($user) {
$user->password = Hash::make($password);
$user->save();
}

Resources