My code used to work properly but now there is an error
(ErrorException (E_NOTICE)Undefined index: password)
I really dont know why, so if you know please help me. I searched google for similar exceptions and try everything I see but still no success ... Here is my code
route.php
Route::resource('login', 'LoginController');
LoginController
public function store(){
/*$credentials = array(
'username' => Input::get('username'),
'password' => Hash::make(Input::get('password')),
);*/
if(Auth::attempt(['active' => 1])) {
// if(Auth::attempt($credentials)){
if(Auth::attempt(Input::only('username', 'password'))){
return Auth::user();
//return Redirect::back()->with('message','You are now logged in!');
//return Redirect::to('/')->with('message','You are now logged in!');
}
else{
//$errors = ['password' => "Username and/or password invalid."];
//return Redirect::back()->withErrors($errors)->withInput(Input::except('password'));
return 'Failed~';
}
}
else{
//$errors = ['password' => "Please check your email to activate your account"];
//return Redirect::back()->withErrors($errors)->withInput(Input::except('password'));
return 'Failed~';
}
}
}
View login/create.blade.php
#section('content')
<div class="col-lg-3"></div>
<div class="form col-lg-6 box">
{{ Form::open(['route' => 'login.store'], array('class' => 'form-horizontal')) }}
{{-- #if ($error = $errors->first('password'))
<div class="alert alert-danger">
{{ $error }}
</div>
#endif--}}
<div class="input-group form-group-md">
<span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
{{ Form::text('username', null,['class' => 'form-control','autofocus'=>'autofocus', 'placeholder' => 'Username']) }}
</div>
<div class="input-group form-group-md">
<span class="input-group-addon"><i class="glyphicon glyphicon-lock"></i></span>
{{ Form::password('password', array('class' => 'form-control', 'placeholder' => 'Password')) }}
</div>
<div class="form-group-md">
Forgot your password?
</div>
<div class="form-group-md">
{{ Form::submit('Log In', array('class' => 'login navbar-btn btn-block form-control', 'autofocus'=>'autofocus')) }}
</div>
<div class="question form-group-md">
{{ Form::label('register', 'Do not have an account?! ') }} Register here!
</div>
{{ Form::close() }}
</div>
<div class="col-lg-3"> </div>
#stop
error
Rewrite your code as below.
$username = Input::get('username');
$password = Input::get('password');
// You also may add extra conditions to the authenticating query
if (Auth::attempt(array('username' => $username, 'password' => $password, 'active' => 1)))
{
// The user is active, not suspended, and exists.
}else{
// user not exist or suspended
}
Refer this link also.
The problem is that the validateCredentials method which is belongs to your class provider EloquentUserProvider expects that the $credentials array have array element called password and expects it to be hashed .
as shown here :
/**
* Validate a user against the given credentials.
*
* #param \Illuminate\Contracts\Auth\Authenticatable $user
* #param array $credentials
* #return bool
*/
public function validateCredentials(UserContract $user, array $credentials)
{
$plain = $credentials['password'];
return $this->hasher->check($plain, $user->getAuthPassword());
}
and you in your code are sending wrong array in the first attempt call
if(Auth::attempt(['active' => 1]))
to solve this you may have to rewrite your code some thing like this ,
public function store()
{
$credentials = array(
'username' => Input::get('username'),
'password' => Hash::make(Input::get('password')),
'active' => 1
);
if(Auth::attempt($credentials)) {
return Auth::user();
} else {
return 'Failed~';
}
}
Related
I am trying to save uploaded image to uploads folder as well as database at the time of user registration, the image name is successfully saved to the database along with user details like name, address, email and etc. I am new to laravel. Please can any one suggest me, thank you.
Please find below is my register.blade.php
#extends('layouts.site')
#section('content')
<div class="login-content">
<a class="hiddenanchor" id="signup">
</a>
<a class="hiddenanchor" id="signin">
</a>
#include('layouts.site-navigation')
#include('errors.errors')
<div class="login_wrapper">
<div class="animate form login_form">
<section class="login_content">
<!-- <form> -->
<h1>Registration Form
</h1>
{!! Form::open(array('url' => URL_USERS_REGISTER, 'method' => 'POST',
'name'=>'formLanguage ', 'novalidate'=>'', 'class'=>"loginform",
'name'=>"registrationForm", 'files'=>'true')) !!}
<div>
</div>
<div>
{{ Form::text('username', $value = null , $attributes =
array('class'=>'form-control',
'placeholder' => getPhrase("username"),
'ng-model'=>'username',
'required'=> 'true',
'ng-class'=>'{"has-error": registrationForm.username.$touched &&
registrationForm.username.$invalid}',
'ng-minlength' => '4',
)) }}
</div>
<div>
{{ Form::text('rollnumber', $value = null , $attributes =
array('class'=>'form-control',
'placeholder' => getPhrase("roll number"),
'ng-minlength' => '2',
)) }}
<div>
{{ Form::text('branch', $value = null , $attributes =
array('class'=>'form-control',
'placeholder' => getPhrase("branch"),
'ng-minlength' => '2',
)) }}
</div>
<div>
{{ Form::text('phone', $value = null , $attributes =
array('class'=>'form-control',
'placeholder' => getPhrase("phone"),
'ng-model'=>'phone',
'ng-pattern' => getRegexPattern('phone'),
'required'=> 'true',
'ng-class'=>'{"has-error": registrationForm.phone.$touched &&
registrationForm.phone.$invalid}',
'ng-minlength' => '10',
)) }}
</div>
<div>
<select id="make" name="place" class="form-control">
<option value="" disabled selected>Interested Work Place
</option>
<option value="Yemmiganur">Yemmiganur
</option>
<option value="Raichur">Raichur
</option>
</select>
</div>
<br>
<div>
Interested To Work In Night Shift:
<input type="radio" name="night_shift" value="Yes" > Yes
<input type="radio" name="night_shift" value="No"> No
</div>
<div class="clearfix">
</div>
<div class="separator">
<p class="change_link">New to site?
<a href="#signup" class="to_register"> Next
</a>
</p>
<div class="clearfix">
</div>
</div>
<br>
<a href="{{URL_USERS_LOGIN}}">
<p class="text-center">{{getPhrase('i_am_having_account')}}
</p>
</a>
</div>
</section>
<div id="register" class="animate form registration_form">
<section class="login_content">
{!! Form::open(array('url' => URL_USERS_REGISTER, 'method' => 'POST',
'name'=>'formLanguage ', 'novalidate'=>'', 'class'=>"loginform",
'name'=>"registrationForm")) !!}
<!-- <form> -->
<h1>Registration Form
</h1>
<div>
{{ Form::email('email', $value = null , $attributes =
array('class'=>'form-control formclass',
'placeholder' => getPhrase("email"),
'ng-model'=>'email',
'required'=> 'true',
'ng-class'=>'{"has-error": registrationForm.email.$touched &&
registrationForm.email.$invalid}',
)) }}
</div>
<div>
{{ Form::password('password', $attributes = array('class'=>'form-
control formclass instruction-call',
'placeholder' => getPhrase("password"),
'ng-model'=>'registration.password',
'required'=> 'true',
'ng-class'=>'{"has-error": registrationForm.password.$touched &&
registrationForm.password.$invalid}',
'ng-minlength' => 5
)) }}
</div>
<div>
{{ Form::password('password_confirmation', $attributes =
array('class'=>'form-control formclass instruction-call',
'placeholder' => getPhrase("password_confirmation"),
'ng-model'=>'registration.password_confirmation',
'required'=> 'true',
'ng-class'=>'{"has-error":
registrationForm.password_confirmation.$touched &&
registrationForm.password_confirmation.$invalid}',
'ng-minlength' => 5,
'compare-to' =>"registration.password"
)) }}
{{ Form::text('aadhar_number', $value = null , $attributes =
array('class'=>'form-control',
'placeholder' => "UID (Aadhaar)",
'required'=> 'true',
'ng-class'=>'{"has-error": registrationForm.aadhar_number.$touched
&& registrationForm.aadhar_number.$invalid}',
'ng-minlength' => '12',
)) }}
<br>
</div>
<fieldset class="form-group" >
<input type="file" class="form-control" name="image"
accept=".png,.jpg,.jpeg" id="image_input">
</fieldset>
<?php $parent_module = getSetting('parent', 'module'); ?>
#if(!$parent_module)
<input type="hidden" name="is_student" value="0">
#else
<div class="row">
<div class="col-md-6">
{{ Form::radio('is_student', 0, true, array('id'=>'free')) }}
<label for="free">
<span class="fa-stack radio-button">
<i class="mdi mdi-check active">
</i>
</span> {{getPhrase('i_am_an_admin')}}
</label>
</div>
<div class="col-md-6">
{{ Form::radio('is_student', 0, true, array('id'=>'free')) }}
<label for="free">
<span class="fa-stack radio-button">
<i class="mdi mdi-check active">
</i>
</span> {{getPhrase('i_am_a_student')}}
</label>
</div>
</div>
#endif
<div class="text-center buttons">
<button type="submit" class="btn btn-default submit"
ng-disabled='!registrationForm.$valid'>
{{getPhrase('register_now')}}
</button>
</div>
{!! Form::close() !!}
<div class="clearfix">
</div>
<div class="separator">
<p class="change_link">Already a member ?
<a href="#signin" class="to_register"> Previous
</a>
</p>
<div class="clearfix">
</div>
</div>
</section>
</div>
</div>
#stop
#section('footer_scripts')
#include('common.validations')
#stop
AuthController.php
<?php
namespace App\Http\Controllers\Auth;
use App\User;
use Validator;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
use \Auth;
use Socialite;
use Exception;
class AuthController extends Controller
{
/*
|--------------------------------------------------------------------------
| Registration & Login Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users, as well as the
| authentication of existing users. By default, this controller uses
| a simple trait to add these behaviors. Why don't you explore it?
|
*/
use AuthenticatesAndRegistersUsers, ThrottlesLogins;
/**
* Where to redirect users after login / registration.
*
* #var string
*/
protected $redirectTo = '/';
protected $dbuser = '';
protected $provider = '';
/**
* Create a new authentication controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware($this->guestMiddleware(), ['except' => 'logout']);
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'username' => 'required|max:255|unique:users',
// 'name' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'aadhar_number' => 'required|max:12|unique:users',
'password' => 'required|min:6|confirmed',
'image' => 'bail',
'place' => 'required',
'night_shift' => 'required',
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return User
*/
protected function create(array $data )
{
$type = 'student';
if($data['is_student'])
$type = 'parent';
$role = getRoleData($type);
$user = new User();
$user->username = $data['username'];
$user->rollnumber = $data['rollnumber'];
$user->branch = $data['branch'];
$user->email = $data['email'];
$user->password = bcrypt($data['password']);
$user->role_id = $role;
$user->image = $data['image'];
$user->place = $data['place'];
$user->night_shift = $data['night_shift'];
$user->phone = $data['phone'];
$user->aadhar_number = $data['aadhar_number'];
$user->slug = $user->makeSlug($user->username);
$user->save();
$user->roles()->attach($user->role_id);
try{
$this->sendPushNotification($user);
sendEmail('registration', array('user_name'=>$user->name,
'username'=>$data['username'], 'to_email' => $user->email,
'password'=>$data['password'], 'aadhar_number' => $user->aadhar_number));
}
catch(Exception $ex)
{
}
flash('success','record_added_successfully', 'success');
$options = array(
'name' => $user->name,
'image' => getProfilePath($user->image),
'slug' => $user->slug,
'role' => getRoleData($user->role_id),
);
pushNotification(['owner','admin'], 'newUser', $options);
return $user;
}
public function sendPushNotification($user)
{
if(getSetting('push_notifications', 'module')) {
if(getSetting('default', 'push_notifications')=='pusher') {
$options = array(
'name' => $user->name,
'image' => getProfilePath($user->image),
'slug' => $user->slug,
'role' => getRoleData($user->role_id),
);
pushNotification(['owner','admin'], 'newUser', $options);
}
else {
$this->sendOneSignalMessage('New Registration');
}
}
}
/**
* This is method is override from Authenticate Users class
* This validates the user with username or email with the sent password
* #param Request $request [description]
* #return [type] [description]
*/
protected function processUpload(Request $request, User $user)
{
if(env('DEMO_MODE')) {
return 'demo';
}
if ($request->hasFile('image')) {
$imageObject = new ImageSettings();
$destinationPath = $imageObject->getProfilePicsPath();
$destinationPathThumb = $imageObject->getProfilePicsThumbnailpath();
$fileName = $user->id.'.'.$request->image->guessClientExtension();
;
$request->file('image')->move($destinationPath, $fileName);
$user->image = $fileName;
Image::make($destinationPath.$fileName)->fit($imageObject-
>getProfilePicSize())->save($destinationPath.$fileName);
Image::make($destinationPath.$fileName)->fit($imageObject-
>getThumbnailSize())->save($destinationPathThumb.$fileName);
$user->save();
}
}
public function postLogin(Request $request)
{
$login_status = FALSE;
if (Auth::attempt(['aadhar_number' => $request->email, 'password' =>
$request->password])) {
// return redirect(PREFIX);
$login_status = TRUE;
}
elseif (Auth::attempt(['email'=> $request->email, 'password' =>
$request->password])) {
$login_status = TRUE;
}
if(!$login_status)
{
return redirect()->back()
->withInput($request->only($this->loginUsername(), 'remember'))
->withErrors([
$this->loginUsername() => $this->getFailedLoginMessage(),
]);
}
/**
* Check if the logged in user is parent or student
* if parent check if admin enabled the parent module
* if not enabled show the message to user and logout the user
*/
if($login_status) {
if(checkRole(getUserGrade(7))) {
if(!getSetting('parent', 'module')) {
return redirect(URL_PARENT_LOGOUT);
}
}
}
/**
* The logged in user is student/admin/owner
*/
if($login_status)
{
return redirect(PREFIX);
}
}
/**
* Redirect the user to the GitHub authentication page.
*
* #return Response
*/
public function redirectToProvider($logintype)
{
if(!getSetting($logintype.'_login', 'module'))
{
flash('Ooops..!', $logintype.'_login_is_disabled','error');
return redirect(PREFIX);
}
$this->provider = $logintype;
return Socialite::driver($this->provider)->redirect();
}
/**
* Obtain the user information from GitHub.
*
* #return Response
*/
public function handleProviderCallback($logintype)
{
try{
$user = Socialite::driver($logintype);
if(!$user)
{
return redirect(PREFIX);
}
$user = $user->user();
if($user)
{
if($this->checkIsUserAvailable($user)) {
Auth::login($this->dbuser, true);
flash('Success...!', 'log_in_success', 'success');
return redirect(PREFIX);
}
flash('Ooops...!', 'faiiled_to_login', 'error');
return redirect(PREFIX);
}
}
catch (Exception $ex)
{
return redirect(PREFIX);
}
}
public function checkIsUserAvailable($user)
{
$id = $user->getId();
$nickname = $user->getNickname();
$name = $user->getName();
$email = $user->getEmail();
$avatar = $user->getAvatar();
$this->dbuser = User::where('email', '=',$email)->first();
if($this->dbuser) {
//User already available return true
return TRUE;
}
$newUser = array(
'name' => $name,
'email'=>$email,
);
$newUser = (object)$newUser;
$userObj = new User();
$this->dbuser = $userObj->registerWithSocialLogin($newUser);
$this->dbuser = User::where('slug','=',$this->dbuser->slug)->first();
// $this->sendPushNotification($this->dbuser);
return TRUE;
}
public function socialLoginCancelled(Request $request)
{
return redirect(PREFIX);
}
}
First, you should urgently consider updating Laravel to newer versions.
Second, I think you are missing enctype="multipart/form-data" accept-charset="UTF-8" in your form tag
I'm trying to update some data with image. The other data is updated but the image still not updated. here's my code
route
Route::get('film/{idFilm}/edit', array('as' => 'film.edit', 'uses' => 'FilmController#edit'));
Route::post('film/{idFilm}/update', array('as' => 'film.update', 'uses' => 'FilmController#update'));
controller
public function edit($idFilm)
{
$film = Film::findOrFail($idFilm);
$genre = Genre::lists('namaGenre', 'idGenre');
if (is_null($film))
{
return Redirect::to('film');
}
return View::make('pengelolaan.film.editfilm', compact('film','genre'));
}
/**
* Update the specified resource in storage.
*
* #param int $id
* #return Response
*/
public function update($idFilm)
{
$rules = array(
'judulFilm' => 'required',
'durasi' => 'required|numeric',
'keterangan' => 'required',
'idGenre' => 'required'
);
$validation = Validator::make(Input::all(), $rules);
if ($validation->fails())
{
return Redirect::to('film/' . $idFilm . '/edit')
->withErrors($validation)
->withInput()
->with('message', 'There were validation errors.');
}
else
{
$films = Film::find($idFilm);
$films->judulFilm=Input::get('judulFilm');
$films->durasi=Input::get('durasi');
$films->keterangan= Input::get('keterangan');
$films->idGenre= Input::get('idGenre');
if(Input::hasFile('foto'))
{
$file=Input::file('foto');
$file->move('img',$file->getClientOriginalName());
$filename=$file->getClientOriginalName();
$films->foto = $filename;
$films->save();
}
else
{
$films->save();
}
Session::flash('message', 'Data Berhasil Diubah');
return Redirect::to('film');
}
}
view
{{Form::model($film, array('route'=>array('film.update', $film->idFilm,'files' => TRUE)))}}
<div class="form-group">
<div class="col-lg-6">
{{ Form::label('judulFilm', 'Judul Film') }}
{{ Form::text('judulFilm', Input::old('judulFilm'), array('class' => 'form-control')) }}
</div>
</div>
<div class="form-group">
<div class="col-lg-6">
{{ Form::label('durasi', 'Durasi Film') }}
{{ Form::text('durasi', Input::old('durasi'), array('class' => 'form-control')) }}
</div>
</div>
<div class="form-group">
<div class="col-lg-6">
{{ Form::label('keterangan', 'Sinopsis Film') }}
{{ Form::textarea('keterangan', Input::old('keterangan'), array('class' => 'form-control')) }}
</div>
</div>
<div class="form-group">
<div class="col-lg-6">
{{ Form::label('idGenre', 'Genre') }}
{{ Form::select('idGenre', $genre,'',array('class'=>'form-control')) }}
</div>
</div>
<div class="form-group">
<div class="col-lg-6">
{{ Form::label('foto', 'Poster') }}
{{ Form::file('foto') }}
</div>
</div>
</br>
<div class="form-group">
<div class="col-lg-6">
<a class="btn btn-default " href="{{ url('film') }}">Batal</a>
{{Form::submit('Simpan', array('type'=>'submit', 'class'=>'btn btn-default'))}}
{{Form::close()}}
There's no error so i don't know whats wrong with it.
Can someone please tell me what's wrong? Thanks in advance
There are few possibilities to face this issue :
Check for have enctype="multipart/form-data" attribute
Check your file size. If your file size is too high increase upload_max_filesize
May be permission dined for your tmp folder. Provide permission for your tem folder. ini_get('upload_tmp_dir');
I have a function:
function nomor_registrasi() {
$sql=mysql_query("select * from pendaftaran order by no_registrasi DESC LIMIT 0,1");
$data=mysql_fetch_array($sql);
$kodeawal=substr($data['no_registrasi'],6,7)+1;
if($kodeawal<10) {
$kode='SMKGJ00'.$kodeawal;
} else if ($kodeawal > 9 && $kodeawal <=99) {
$kode='SMKGJ0'.$kodeawal;
} else {
$kode='SMKGJ'.$kodeawal;
}
return $kode;
}
If a user registers from a form, the user will have no_registrasi, for example: last no_registrasi record in the table is SMKGJ006, so the user will have SMKGJ007, etc..
I'm starting learning the php framework: laravel.
How can I code this function using laravel?
I use laravel 4!
If you want to put your function to run when user register you need to put it in Controller that respond for registration of users.
The Controllers are in folder /app/controllers .
If you recent(1 minute ago) installed **laravel 4.1 and not have the Controller that respond for registration of users (like me, after installation I have a page on with is only image and you arrived and no link to register and login like after installation of yii), when you need to create it.
To create controller UsersController put in /app/controllers file with name UsersController.php and code:
<?php
class UsersController extends BaseController {
//!!show the form for registration from root /app/views/some_file name_like_register.blade.php in witch is html form
public function getRegister() {
return View::make('users/register');
}
//!! register user when post data come from form
public function postRegister() {
//Here you can put your function
$rules = User::$validation;
$validation = Validator::make(Input::all(), $rules);
if ($validation->fails()) {
return Redirect::to('public/users/register')->withErrors($validation)->withInput();
}
$user = new User();
$user->fill(Input::all());
$id = $user->register();
return $this->getMessage("Registered successfull.");
}
}
Add changes to User model. After
class User extends Eloquent implements UserInterface, RemindableInterface {
add
//form validation
public static $validation = array(
'email' => 'required|email|unique:users',
'username' => 'required|alpha_num|unique:users',
'password' => 'required|confirmed|min:6',
);
//for registration
protected $fillable = array('username', 'email', 'password');
//
public function register() {
//Here you can put your function
$this->password = Hash::make($this->password);
$this->activationCode = $this->generateCode();
$this->save();
Log::info("User [{$this->email}] registered. Activation code: {$this->activationCode}");
/*$this->sendActivationMail();*/ //send email with activation code, set 1 to isActive value
return $this->id;
}
protected function sendActivationMail() { /*do*/}
protected function generateCode() {
return Str::random();
}
Make file with name register.blade.php in /app/views/ with code:
#section('title')
#section('content')
<div class="container">
#if ($errors->all())
<div class="alert alert-danger">
#foreach ($errors->all() as $error)
<p>{{ $error }}</p>
#endforeach
</div>
#endif
<h1>Registration</h1>
{{ Form::open(array('url' => '/users/register', 'role' => 'form', 'class' => 'form-horizontal')) }}
<div class="form-group">
{{ Form::label('email', 'E-Mail', array('class' => 'col-sm-2 control-label')) }}
<div class="col-sm-5">
{{ Form::email('email', null, array('class' => 'form-control')) }}
</div>
</div>
<div class="form-group">
{{ Form::label('username', 'login', array('class' => 'col-sm-2 control-label')) }}
<div class="col-sm-5">
{{ Form::text('username', null, array('class' => 'form-control')) }}
</div>
</div>
<div class="form-group">
{{ Form::label('password', 'password', array('class' => 'col-sm-2 control-label')) }}
<div class="col-sm-5">
{{ Form::password('password', array('class' => 'form-control')) }}
</div>
</div>
<div class="form-group">
{{ Form::label('password_confirmation', 'retype pass', array('class' => 'col-sm-2 control-label')) }}
<div class="col-sm-5">
{{ Form::password('password_confirmation', array('class' => 'form-control')) }}
</div>
</div>
<div class="form-group">
<div class="col-sm-2"> </div>
<div class="col-sm-5">
<button type="submit" class="btn btn-primary">Go</button>
</div>
</div>
{{ Form::close() }}
In table user add your registraci cell. Table structure is
Schema::create('users', function(Blueprint $table) {
$table->increments('id');
$table->string('email')->unique();
$table->string('password', 60);
$table->string('username')->unique();
$table->boolean('isAdmin');
$table->boolean('isActive')->index();
$table->string('activationCode');
$table->rememberToken();
$table->timestamps();
// also add your registraci
$table->string('registraci', 200);
});
To turn on database driver open /app/config/database.php and change if need
//select mysql or other
'default' => 'mysql'
...
//database and other change here
'mysql' => array(
'driver' => 'mysql',
'host' => 'localhost',
'database' => 'laravel',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
)
If I lost something you will get errors messages not like oops but real problems
To see errors go to /app/config/app.php and set to
'debug' => true,
Add a column with name no_registrasi in laravel table with users and use your old code when register new user, only change table name and other columns name.
https://laravel.com/docs/5.0/schema
Schema::table('users', function($table)
{
$table->string('no_registrasi');
});
I want the user to be able to update his own password. i get three inputs while in database i have the password field together with the username and email. I don't really know the flow of controller hope u can help me out.
my controller:
public function changepass() {
$user = Auth::user();
$rules = array(
'old_password' => 'required|alphaNum|between:4,16',
'password' => 'required|alphaNum|between:4,16|confirmed'
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) {
return Redirect::action('HomeController#getpass', $user->id)->withErrors($validator);
} else {
if (!Hash::check(Input::get('old_password'), $user->password)) {
return Redirect::action('HomeController#getpass', $user->id)->withErrors('Old password does not match!');
} else {
$user->password = Hash::make(Input::get('password'));
$user->save();
return Redirect::action('HomeController#getpass', $user->id)->withMessage("Password has been changed successfully!");
}
}
My view:
#extends('master')
#section('content')
<div class="span8 well" style="opacity: 0.9">
<h4>Change password: </h4>
{{ Form::open(array('url' => 'changepass/', 'method'=>'POST')) }}
{{Form::hidden('id',Auth::user()->id)}}
<div class="form-group">
{{ Form::password('old_password', array('class'=>'form-control', 'placeholder'=>'Old Password')) }}<br>
{{ Form::password('new_password', array('class'=>'form-control', 'placeholder'=>'New Password')) }}<br>
{{ Form::password('confirm_new_password', array('class'=>'form-control', 'placeholder'=>'Confirm New Password')) }}
</div>
{{ Form::submit('Update', array('class' => 'btn btn-success')) }}
</div>
#stop
//Route
Route::post('changepass', 'HomeController#changepass');
When a user is created a random password (and a auth code) will be created and send with an email to the user.
When clicked on the link in the email the user status will be 1 (so active) and the user will be able to change his password right away.
Now it doesn't work as I want to.
UserController:
public function store(CreateUserRequest $request, User $user, Attribute $attribute)
// some unnecessary code
if ((Input::get('usertype_id')) > 1) {
$randomPassword = str_random(8);
$user->password = Hash::make($randomPassword);
$authentication_code = str_random(12);
$user->authentication_code = $authentication_code;
$user->active = 0;
};
$user->save();
if ((Input::get('usertype_id')) > 1) {
// Email sturen met verficatie code
$email = Input::get('email');
Mail::send('emails.user', ['user' => $user, 'password' => $randomPassword, 'authentication_code' => $authentication_code], function ($message) use ($email) {
$message->to($email, 'Lilopel')->subject('Lilopel: Verify your account!');
});
};
public function confirmUser($authentication_code)
{
if (!$authentication_code)
{
return 'auth code not found!';
}
$user = User::where('authentication_code', '=', $authentication_code)->first();
if (!$user)
{
return 'user not found!';
}
$user->active = 1;
$user->save();
Session::put('user_id', $user->id);
return view('user.setpassword', ['user' => $user]);
//return redirect()->route('user.setPassword', [$user_id]);
}
public function setPassword(SetPasswordRequest $request)
{
$user_id = Session::get('user_id');
$user = $this->user->find($user_id);
$user->fill($request->only('password'));
$user->save();
}
Route:
Route::get('user/verify/{authenticationCode}', 'UserController#confirmUser');
Route::get('user/password', 'UserController#setPassword');
View:
{!! Form::model($user, ["route"=>['user.setPassword', $user->id] , "method" => 'PATCH']) !!}
<div class="form-group {{ $errors->has('password') ? 'has-error' : '' }}">
{!! Form::label('password', trans('common.password'), ['class' => 'form-label col-sm-3 control-label
text-capitalize']) !!}
<div class="col-sm-6">
{!! Form::password('password', ['name' => 'password', "class"=>"form-control","placeholder" =>
trans('common.password') ]) !!}
{!! $errors->first('password', '<span class="help-block">:message</span>') !!}
</div>
</div>
<div class="form-group {{ $errors->has('confirm_password') ? 'has-error' : '' }}">
{!! Form::label('password_confirmation', trans('common.confirmpassword'), ['class' => 'form-label
col-sm-3 control-label text-capitalize']) !!}
<div class="col-sm-6">
{!! Form::password('password_confirmation', ['name' => 'password_confirmation',
"class"=>"form-control","placeholder" => trans('common.confirmpassword') ]) !!}
{!! $errors->first('password_confirmation', '<span class="help-block">:message</span>') !!}
</div>
</div>
{!! Form::submit( trans('common.edit'), ["class"=>"btn btn-primary text-capitalize center-block "]) !!}
{!! Form::close() !!}
Email links works, the status of the user gets active, but then the .blade will give a Route [user.setPassword] not defined. (View: public_html/server2/resources/views/user/setpassword.blade.php) error.
work togetherTo use the route as you do, you need a named route.
Change this
Route::get('user/password', 'UserController#setPassword');
to this
Route::get('user/password', [
'as' => 'user.setPassword',
'uses' => 'UserController#showProfile'
]);
Also, make sure the HTTP verbs of the route and your form's method work together.