I have created a login page in which user login in with their credentials i.e patientId and contactNumber but after being logged in, the CSRF token is also displaying login credentials along with the token.Also I am using APIs for login and other stuff.
This is the output I am getting:
http://127.0.0.1:8000/login1?_token=BugYniw96HnJ6C8gjjcpzSruW0CwDdq8JW7kD7Oz&patientId=33488&contactNumber=08732837489
This is my login blade file:
<form method="GET" action="{{route('login1')}}" name="myForm" class="login100-form validate-form" >
<input type="hidden" name="_token" value="{{ csrf_token()}}">
<span class="login100-form-title">
User Login
</span>
<div class="wrap-input100 validate-input" data-validate="Mr.No is required">
<input class="input100" name="patientId" id="patientId" placeholder="Enter MR Number" >
<span class="focus-input100"></span>
<span class="symbol-input100">
<i class="fa fa-user" aria-hidden="true"></i>
</span>
</div>
<div class="wrap-input100 validate-input" data-validate="Contact Number is required">
<input class="input100" name="contactNumber" id="contactNumber" placeholder="Enter Contact Number">
<span class="focus-input100"></span>
<span class="symbol-input100">
<i class="fa fa-lock" aria-hidden="true"></i>
</span>
</div>
<div class="container-login100-form-btn">
<button class="login100-form-btn" type="submit">
Login
</button>
</div>
<div class="text-center p-t-136">
<a class="txt2" href="#">
</a>
</div>
</form>
This is a web route file:
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\MainController;
use App\Http\Middleware\VerifyCsrfToken;
Route::get('/', function () {
return view('login1');
});
Route::get('/login1', [MainController::class, 'successlogin'])->name('login1');
This is my controller file:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\SessionClass;
use Illuminate\Support\Facades\Http;
use App\Http\Controllers\HostClass;
use Illuminate\Support\Facades\Session;
class MainController extends Controller
{
public function successlogin(Request $req)
{
$host = new HostClass();
$obj = new SessionClass();
$obj->sethalfpatientId($req->patientId);
$response = Http::post($host->getserverIp().'/patientInformation',[
"patientId"=> $req->patientId,
"contactNumber"=> $req->contactNumber,
"orgId"=>"332",
"sessionId"=> "3"
]);
$data = json_decode($response, true);
if($data == null){
echo "error";
$notification = array(
'message' => 'User Does not Exists!',
'alert-type' => 'error'
);
return back()->with($notification);
}
else{
$obj->setpatientId($data['patientId']);
$obj->setcontactNumber($data['contactNumber']);
$response2 = Http::post($host->getserverIp().'/searchPatientReports',[
"patientId"=> $obj->getpatientId(),
"departmentId"=> "128"
]);
$data2 = json_decode($response2, true);
$response3 = Http::post($host->getserverIp().'/patientVisits',[
"patientId"=> $obj->getpatientId()
]);
$data3 = json_decode($response3, true);
Session::put('user', $data);
$listappointment = ($data['listAppointments']);
return view('dashboard', compact(['data','data2','data3','listappointment']));
}
}
use POST method so the data dont show in the url
<form method="POST" action="{{route('login1')}}" name="myForm" class="login100-form validate-form" >
And change the route to accept post method
Route::post('/login1', [MainController::class, 'successlogin'])->name('login1');
Related
I am creating the simple login form using laravel 7.i want to check the username and password match.it is a match redirect the home. if it does not redirect the login page again show the error username or password does not match. I tried the below code I got the error Call to undefined method App\User::attempt()
Login Controller.
public function check(Request $request)
{
$uname = $request->uname;
$password = $request->password;
$user = User::where('uname',$a)->get()->last();
$pass = User::where('password',$b)->get()->last();
if (User::attempt(array('uname' => $uname , 'password' => $password ))){
return "success";
}
else {
return "Wrong Credentials";
}
}
view Login
#extends('layout')
#section('content')
<div class="row">
<div class="col-lg-12 margin-tb">
<div class="pull-left">
<h2>Login</h2>
</div>
<div class="pull-right">
</div>
</div>
</div>
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<div class="row">
<form action="{{ route('login.check') }}" method="POST">
#csrf
<div class="col-sm-4">
<div class="left">
<strong>UserName</strong>
<input type="text" name="uname" class="form-control" placeholder="UName">
</div>
<div class="left">
<strong>Password</strong>
<input type="password" class="form-control" name="password" placeholder="Password"></textarea>
</div>
</br>
<div class="left">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</form>
</div>
Model User
protected $fillable = [
'name', 'email', 'password',
];
you need to replace User::attempt with auth()->attempt
another thing you don't need to check uname and passowrd manually laravel do that for you inside the attempt method so it would be more efficient if
you delete those two lines
$user = User::where('uname',$a)->get()->last();
$pass = User::where('password',$b)->get()->last();
finally, depends on your User model you have name not uname so you need to update it like this
if (auth()->attempt(array('name' => $uname , 'password' => $password ))){
return "success";
} else {
return "Wrong Credentials";
}
With laravel 7 /livewire 1.3 app in login form I got errors on invalid form with code:
public function submit()
{
$loginRules= User::getUserValidationRulesArray();
$this->validate($loginRules);
and shows error message near with any field
I want on login fail to add flash message and reading at
https://laravel.com/docs/7.x/validation
I try to make :
$request = request();
$loginRules= User::getUserValidationRulesArray('login');
$validator = Validator::make($request->all(), $loginRules);
if ($validator->fails()) {
session()->flash('danger_message', 'Check your credentials !');
return redirect()->to('/login');
}
I got flash message, but validation errors for any field is lost.
If I try to make :
$request = request();
$loginRules= User::getUserValidationRulesArray('login');
$validator = Validator::make($request->all(), $loginRules);
if ($validator->fails()) {
session()->flash('danger_message', 'Check your credentials !');
return redirect('/login')
->withErrors($validator)
->withInput();
}
and I got error :
Method Livewire\Redirector::withErrors does not exist.
in routes/web.php I have :
Route::livewire('/login', 'login')->name('login');
MODIFIED :
In component app/Http/Livewire/Login.php :
<?php
namespace App\Http\Livewire;
use App\User;
use Illuminate\Support\Facades\Validator;
use Livewire\Component;
use Auth;
use DB;
use App\Config;
use Cartalyst\Sentinel\Laravel\Facades\Sentinel;
class Login extends Component
{
public $form= [
'email'=>'admin#mail.com',
'password'=> '111111',
];
private $view_name= 'livewire.auth.login';
public function submit()
{
$request = request();
$loginRules= User::getUserValidationRulesArray('login');
$validator = Validator::make($request->all(), $loginRules);
if ($validator->fails()) {
session()->flash('danger_message', 'Check your credentials !');
return;
// return redirect()->to('/login');
}
$user = Sentinel::findByCredentials(['email' => $this->form['email']]);
if (empty($user)) {
session()->flash('danger_message', 'User "' . $this->form['email'] . '" not found !');
...
and template resources/views/livewire/auth/login.blade.php :
<article >
#include('livewire.common.alert_messages')
<form class="form-login" wire:submit.prevent="submit">
<div class="card">
#if ($errors->any())
Check your login credentials
#endif
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
<div class="card-body card-block">
<h3 class="card-header">
<span class="spinner-border" role="status" wire:loading>
<span class="sr-only">Loading...</span>
</span>
Login
</h3>
<h4 class="card-subtitle">Use your credentials</h4>
<dl> <!-- email FIELD DEFINITION -->
<dt>
<label class="col-form-label" for="email">Email:<span class="required"> * </span></label>
</dt>
<dd>
<input
wire:model.lazy="form.email"
name="email"
id="email"
class="form-control"
placeholder="Your email address"
autocomplete=off
>
#error('form.email')
<div class="validation_error">{{ clearValidationError($message,['form.'=>'']) }}</div> #enderror
</dd>
</dl> <!-- <dt> email FIELD DEFINITION -->
<dl> <!-- password FIELD DEFINITION -->
<dt>
<label class="col-form-label" for="password">Password:<span class="required"> * </span></label>
</dt>
<dd>
<input type="password"
wire:model.lazy="form.password"
id="password"
name="password"
class="form-control"
placeholder="Your password"
autocomplete=off
>
#error('form.password')
<div class="validation_error">{{ clearValidationError($message,['form.'=>'']) }}</div> #enderror
</dd>
</dl> <!-- <dl> password FIELD DEFINITION -->
</div> <!-- <div class="card-body card-block"> -->
<section class="card-footer row_content_right_aligned">
<button type="reset" class="btn btn-secondary btn-sm m-2">
Reset
</button>
<button type="submit" class="btn btn-primary btn-sm m-2 ml-4 mr-4 action_link">
Submit
</button>
</section>
</div> <!-- <div class="card"> -->
</form>
</article>
Which way is valid ?
Thanks in advance!
Before render method you can check if errorBag has items:
public function render()
{
if(count($this->getErrorBag()->all()) > 0){
$this->emit('error:example');
}
return view('livewire-component-view');
}
The beauty of Livewire is that you don't necessarily need to redirect to flash a message, you can display messages by setting properties on your component, and conditionally rendering them in your view. In this particular case, there's already logic readily available, you just have to check the errors-object being exposed by the validation.
In your view, all you have to do is check #if ($errors->any()) - if that's true, display your message. This is a Laravel feature, which Livewire implements. When any validation fails, an exception is thrown and intercepted, and the $errors variable gets exposed to your view. This means that whenver you do $this->validate(), and the validation fails, you can access the errors within $errors.
<div>
#if ($errors->any())
Check your login credentials
#endif
<form wire:submit.prevent="submit">
<input type="text" wire:model="email">
#error('email') <span class="error">{{ $message }}</span> #enderror
<input type="password" wire:model="password">
#error('password') <span class="error">{{ $message }}</span> #enderror
<button type="submit">Submit</button>
</form>
</div>
Use the $rules attribute to declare the rules, validate those rules with $this->validate() and Livewire will do most of the work for you. You do not need to return any redirects, or use session()->flash(). The session-state will not be flashed, because you don't perform a new page load.
class Login extends Component
{
public $form = [
'email' => 'admin#mail.com',
'password' => '111111',
];
protected $rules;
private $view_name = 'livewire.auth.login';
public function submit()
{
$this->rules = User::getUserValidationRulesArray('login');
$this->validate();
// No need to do any more checks, $errors will now be updated in your view as the exception is thrown
// Proceed with submitting the form
i can get the value of every other input in the form into validator and so is the select option values too but while the other request data pass along to the database the select option value always turns up empty. Here is my code...thanks in advance
Here is the Register Controller
<?php
namespace App\Http\Controllers\Admin\Auth;
use App\Admin;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
class RegisterController extends Controller
{
/**
* Show the login form.
*
* #return \Illuminate\Http\Response
*/
public function showRegisterForm()
{
return view('admin.auth.register',[
'title' => 'Create A New Administrator On This Page.',
'registerRoute' => 'admin.register',
]);
}
/**
* Create a new admin instance after a valid registration.
*
* #param array $data
* #return \App\Admin
*/
public function create(Request $request)
{
$this->validate(request(),[
'firstname' => 'required|string|max:255|alpha|min:2',
'lastname' => 'required|string|max:255|alpha|min:2',
'email' => 'required|string|email|max:255|unique:admins',
'privilege' => 'required|numeric',
'consent' => 'required',
]);
$newAdminGeneratedPassword = unique_random('admins', 'password', 10);
$admin = Admin::Create([
'firstname' => $request['firstname'],
'lastname' => $request['lastname'],
'email' => $request['email'],
'privilege' => $request['privilege'],
'password' => Hash::make($newAdminGeneratedPassword),
]);
return redirect()->to('/admin/register')->with('admincreated', 'New Administrator with Privileges Created');
}
}
Here is the HTML FORM
#extends('layouts.app')
#section('title')
OneNaira© Register A New OneNaira Initiative Administrator
#endsection
#section('content')
<!--HOME PAGE NAVBAR-->
<div class="ui top attached pink inverted secondary menu">
<div class="ui container">
<div class="header item">One₦aira</div>
<a class="toc item">
<i class="sidebar icon"></i>
</a>
<div class="right menu" id="large_menu">
Create A New Agent
Manage Existing Agents
Manage Agent Payments
Create A New Administrator
Manage Existing Administrators
Sign Out
</div>
</div>
</div>
<!--SIDEBAR MENU-->
<div class="ui inverted vertical sidebar menu">
Create A New Agent
Manage Existing Agents
Manage Agent Payments
Create A New Administrator
Manage Existing Administrators
Sign Out
</div>
<!--PAGE CONTAINER-->
<div class="ui stackable grid" id="page_container">
<div class="sixteen wide column">
<div class="ui container">
#if(session('admincreated'))
<div class="ui floating info message">
<i class="close icon"></i>
{{ session('admincreated') }}
</div>
#endif
<div class="ui raised very padded segment">
<div class="ui dividing pink header">
One₦aira
<div class="sub header">{{ $title }}</div>
</div>
<form action="{{ route($registerRoute) }}" class="ui form" method="POST">
{{ csrf_field() }}
<div class="field">
<label>{{ __('Name:') }}</label>
<div class="two fields">
<div class="field">
<input type="text" name="firstname" placeholder="First" value="{{ old('firstname') }}" required autofocus>
#if ($errors->has('firstname'))
<div class="ui negative message">
<p>
{{ $errors->first('firstname') }}
</p>
</div>
#endif
</div>
<div class="field">
<input type="text" name="lastname" placeholder="Last" value="{{ old('lastname') }}" required autofocus>
#if ($errors->has('lastname'))
<div class="ui negative message">
<p>
{{ $errors->first('lastname') }}
</p>
</div>
#endif
</div>
</div>
</div>
<div class="field">
<label>{{ __('E-mail:') }}</label>
<input type="email" name="email" id="email" placeholder="Please Enter A Valid Email Address" value="{{ old('email') }}" required>
#if ($errors->has('email'))
<div class="ui negative message">
<p>
{{ $errors->first('email') }}
</p>
</div>
#endif
</div>
<div class="disabled field">
<label>{{ __('Password:') }}</label>
<input type="password" name="password" id="password" placeholder="This Password will be Automatically Generated" required value="1234567890">
#if ($errors->has('password'))
<div class="ui negative message">
<p>
{{ $errors->first('password') }}
</p>
</div>
#endif
</div>
<div class="disabled field">
<label>{{ __('Verify Password:') }}</label>
<input type="password" name="password_confirmation" id="password-confirm" placeholder="This Password will be Automatically Generated" required value="1234567890">
</div>
<div class="field">
<label>{{ __('Privilege:') }}</label>
<select class="ui dropdown" name="privilege">
<option value="">Privilege</option>
<option value="2">Administrator</option>
<option value="1">Super Administrator</option>
<option value="0">Root Administrator</option>
</select>
#if ($errors->has('privilege'))
<div class="ui negative message">
<p>
{{ $errors->first('privilege') }}
</p>
</div>
#endif
</div>
<div class="field">
<div class="ui checkbox">
<input type="checkbox" name="consent" id="consent" tabindex="0" class="hidden" required>
<label>{{ __('I Consent To Creating This Administrator and Granting the Delegated Privileges') }}</label>
#if ($errors->has('consent'))
<div class="ui negative message">
<p>
{{ $errors->first('consent') }}
</p>
</div>
#endif
</div>
</div>
<button class="ui pink button" type="submit">{{ __('Create Administrator') }}</button>
</form>
<div class="ui divider"></div>
</div>
</div>
</div>
</div>
<div class="push-50"></div>
#endsection
#section('footer')
<!--FOOTER-->
<div class="ui stackable pink inverted secondary pointing menu" id="footer">
<div class="ui container">
<a class="item">© OneNaira, 2019.</a>
<div class="right menu">
<a class="item">
<script>
var todaysDate = new Date();
document.write(todaysDate);
</script>
</a>
</div>
</div>
</div>
#endsection
Here is my Routes
<?php
use Illuminate\Support\Facades\Input;
use App\Grant;
use App\Slot;
use App\Events\ProgressUpdaterEvent;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
//Index Route
Route::get('/', function () {
return view('index');
});
//Auth Verify Locking Routes
Auth::routes(['verify' => true]);
//Page Routes
Route::get('/checkgrants', 'GrantController#index')->middleware('auth');
Route::get('/dashboard', 'HomeController#index')->name('dashboard')->middleware('auth')->middleware('verified');
Route::view('/accountsettings', 'accountsettings')->middleware('auth');
Route::get('/wallet', 'WalletController#index')->middleware('auth');
Route::view('/faq', 'faq');
Route::view('/policy', 'policy');
// Log Out Routes
Route::get('/logout', function(){Auth::logout(); return Redirect::to("/login")->with('message', 'You have been successfully logged out');});
//Grant Search Route
Route::any('/searchgrant', function() {
$q = Input::get ('grant_id');
$grant = Grant::where('gid', $q)->get();
if (count($grant) > 0)
{
return view('checkgrants')->withDetails($grant)->withQuery($q);
}
else {
return Redirect::back()->with('status', 'Grant Not Found !. It might be found the next time you try');
}
});
//Route User Edit and Update Route
Route::resource('users', 'UserController');
//Route For SLOT Reservation
Route::resource('slots', 'SlotController');
// Laravel 5.1.17 and above for paystack
Route::post('/pay', 'PaymentController#redirectToGateway')->name('pay');
Route::get('/payment/callback', 'PaymentController#handleGatewayCallback');
//Route For Pusher Testing
Route::get('event', function(){
$slotallcount = Slot::all()->count();
event(new ProgressUpdaterEvent($slotallcount));
});
// Admin Grouped Routes
Route::prefix('/admin')->name('admin.')->namespace('Admin')->group(function(){
Route::namespace('Auth')->group(function(){
//Login Routes
Route::get('/login','LoginController#showLoginForm')->name('login');
Route::post('/login','LoginController#login');
Route::get('/logout','LoginController#logout')->name('logout');
//Register Routes
Route::get('/register', 'RegisterController#showRegisterForm')->name('register');
Route::post('/register', 'RegisterController#create');
//Forgot Password Routes
Route::get('/password/reset','ForgotPasswordController#showLinkRequestForm')->name('password.request');
Route::post('/password/email','ForgotPasswordController#sendResetLinkEmail')->name('password.email');
//Reset Password Routes
Route::get('/password/reset/{token}','ResetPasswordController#showResetForm')->name('password.reset');
Route::post('/password/reset','ResetPasswordController#reset')->name('password.update');
});
//Route For Administrator Dashboard Points Directly To Create Agent Page
Route::get('/dashboard', 'HomeController#index')->name('dashboard');
});
and here is my migrations please help
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateAdminsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('admins', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('firstname', 100);
$table->string('lastname', 100);
$table->smallInteger('privilege');
$table->string('email')->unique();
$table->string('password', 255);
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('admins');
}
}
You forgot to add "privilege" field in $fillable array of Model
I'm succeed to send mail from contact form, and now my requirement is to get automated success reply to the users input email address when submitting the form. please help me on this
ContactUsController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
use App\Mail\ContactUs;
class ContactUsController extends Controller
{
function index()
{
return view('home/contactus');
}
function send(Request $request)
{
$this->validate($request,[
'name' => 'required',
'email' => 'required|email',
'subject' => 'required',
'message' => 'required'
]);
$data = array(
'name' => $request->name,
'email' => $request->email,
'subject' => $request->subject,
'message' => $request->message
);
\Mail::to('xxx#mail.com')->send(new ContactUs($data));
return back()->with('success', 'Thanks for contacting us! We will get back to you soon.');
}
}
ContactUs
<?php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;
class ContactUs extends Mailable
{
use Queueable, SerializesModels;
public $data;
public function __construct($data)
{
$this->data = $data;
}
public function build()
{
return $this->from('xxxx#mail.com')
->subject('Customer Feedback')
->view('dynamic_email_template')
->with('data', $this->data);
}
}
Form
<div class="form">
<h4>Send us a message</h4>
#if (count($errors) > 0)
<div class="alert alert-danger">
<button type="button" class="close" data- dismiss="alert">×</button>
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
#if ($message = Session::get('success'))
<div class="alert alert-success alert-block">
<button type="button" class="close" data- dismiss="alert">×</button>
<strong>{{ $message }}</strong>
</div>
#endif
<form method="post" action="{{url('contactus/send')}}" autocomplete="off">
{{ csrf_field() }}
<div class="form-group">
<input type="text" name="name" for="name" class="form-control" id="name" placeholder="Your Name" data-rule="minlen:4" data-msg="Please enter at least 4 chars" />
<div class="validation"></div>
</div>
<div class="form-group">
<input type="email" class="form-control" name="email" for="email" id="email" placeholder="Your Email" data-rule="email" data-msg="Please enter a valid email" />
<div class="validation"></div>
</div>
<div class="form-group">
<input type="text" class="form-control" name="subject" for="subject" id="subject" placeholder="Subject" data-rule="minlen:4" data-msg="Please enter at least 8 chars of subject" />
<div class="validation"></div>
</div>
<div class="form-group">
<textarea class="form-control" name="message" for="message" rows="5" data-rule="required" data-msg="Please write something for us" placeholder="Message"></textarea>
<div class="validation"></div>
</div>
<div class="text-center">
<button type="submit" name="send" title="Send Message">Send Message</button>
</div>
</form>
</div>
dynamic_email_template
<p>Hi, This is {{ $data['name'] }} "{{ $data['email'] }}"</p> </br>
<p>{{ $data['subject'] }}</p> </br>
<p>I have some query like "{{ $data['message'] }}".</p> </br>
<p>It would be appriciative, if you gone through this feedback.</p>
You need to create email template same like your view file, lets say contact_us_email.blade.php. In this file add this content
contact_us_email.blade.php
<html>
<body>
<h2>Hi, This is {{ $data['name'] }} "{{ $data['email'] }}"</h2><br>
<p>Subject: {{ $data['subject'] }}</p> <br>
<p>I have some query like <b>"{{ $data['message'] }}"</b>. <br>
<p>It would be appriciative, if you gone through this feedback.</p>
</body>
</html>
NOTE: Add css or styling according to your need. this is basic html
Edit: To send confirmation email to user
For success confirmation to user, you can create another email template like
contact_us_thank_you_email.blade.php
<html>
<body>
<h2>Hello, {{ $data['name'] }} "{{ $data['email'] }}"</h2><br>
<p>Thank You for your interest...blah blah blah</p> <br>
<p>Our team will contact you soon</p> <br>
</body>
</html>
Now in your ContactUsController, replace
\Mail::to('xxx#mail.com')->send(new ContactUs($data));
with
Mail::send('contact_us_email', $data, function ($message) use ($data) {
$message->from('xxx#mail.com', 'xxx');
$message->to('xxx#mail.com')->subject($data['subject']);
});
Mail::send('contact_us_thank_you_email', $data, function ($message) use ($data) {
$message->from('xxx#mail.com', 'xxx');
$message->to($data['email'])->subject('Thank you for the interest');
});
And I think you are good to go with this. I hope this is what you are asking for.
I am working on Code Igniter and stuck in a place where I need to change the password of a signed-in user. I need help in picking up the user id of the signed-in user and through it I want to update the password of that user.
The following are the images of controller and models created of the project respectively.
Create html link:
<i class="fa fa-circle-o"></i>Change password
Create user controller:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class User extends CI_Controller
{
public function __construct()
{
parent::__construct();
// Load form helper library
$this->load->helper('form');
// Load form validation library
$this->load->library('form_validation');
// Load session library
$this->load->library('session');
$this->load->model('Data_model');
}
public function changePassword()
{
$web = array();
$web['title'] = 'Change password';
$web['content'] = 'web/password';
$this->form_validation->set_rules('old_password', 'Old password', 'required|callback_check_password');
$this->form_validation->set_rules('new_password', 'New password', 'required');
$this->form_validation->set_rules('confirm_password', 'Confirm password', 'required|matches[new_password]');
if ($this->form_validation->run() == FALSE) {
$this->load->view('web_template',$web);
} else {
$id = $this->user_id;
$data = array(
'user_password' => $this->input->post('new_password'),
);
$this->Common_model->Data_model('user_login', $data, 'id', $id);
$this->session->set_flashdata('msg', 'Password changed Successfully');
redirect('user/changePassword');
}
}
function check_password($password) {
if($this->user_id)
$id = $this->user_id;
else
$id = '';
$result = $this->Data_model->check_user_password($id, $password);
if($result > 0)
$response = true;
else {
$this->form_validation->set_message('check_password', 'Old password is wrong');
$response = false;
}
return $response;
}
}
Change password html page in view:
<section class="content">
<div class="box">
<div class="box-header with-border">
<h3 class="box-title"><?php echo $title; ?></h3>
<div class="box-tools pull-right">
<button type="button" class="btn btn-box-tool" data-widget="collapse" data-toggle="tooltip" title="Collapse">
<i class="fa fa-minus"></i></button>
</div>
</div>
<?php
$attributes = array('class' => 'form-horizontal', 'id' => 'changePassword');
echo form_open('user/changePassword', $attributes);
?>
<div class="box-body">
<?php if (!empty($this->session->flashdata('msg'))) : ?>
<div class="alert alert-success alert-dismissable alertDiv"> <?php echo $this->session->flashdata('msg'); ?> </div>
<?php endif; ?>
<div class="row">
<div class="col-md-offset-2 col-md-8">
<div class="form-group">
<label for="inputEmail3" class="col-md-2 control-label">Old password</label>
<div class="col-md-8">
<input type="password" name="old_password" value="<?php echo (isset($form_data) ? $form_data->old_password : set_value('old_password')); ?>" class="form-control" id="old_password" placeholder="Old password">
<?php echo form_error('old_password', '<div class="error">', '</div>'); ?>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-offset-2 col-md-8">
<div class="form-group">
<label for="inputEmail3" class="col-md-2 control-label">New password</label>
<div class="col-md-8">
<input type="password" name="new_password" value="<?php echo (isset($form_data) ? $form_data->new_password : set_value('new_password')); ?>" class="form-control" id="new_password" placeholder="New password" autocomplete="off">
<?php echo form_error('new_password', '<div class="error">', '</div>'); ?>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-offset-2 col-md-8">
<div class="form-group">
<label for="inputEmail3" class="col-md-2 control-label">Confirm Password</label>
<div class="col-md-8">
<input type="password" name="confirm_password" value="<?php echo (isset($form_data) ? $form_data->confirm_password : set_value('confirm_password')); ?>" class="form-control" id="confirm_password" placeholder="Confirm Password" autocomplete="off">
<?php echo form_error('confirm_password', '<div class="error">', '</div>'); ?>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-offset-5" style="margin-top: 10px;">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</div>
<?php form_close(); ?>
</div>
<!-- /.box -->
</section>
Create Data_model in model add this function:
// Update data to table
public function update($table, $data, $primaryfield, $id)
{
$this->db->where($primaryfield, $id);
$q = $this->db->update($table, $data);
return $q;
}
//Check the old password:
function check_user_password($id = '', $password) {
$this->db->where('user_password', $password);
$this->db->where('id', $id);
return $this->db->get('user_login')->num_rows();
}