This question already has answers here:
Validation error in Laravel - $errors array does not get populated after the validation failure
(3 answers)
Closed 6 years ago.
I'm trying to validate a login/signup system in Laravel 5.2.
I'm using welcome.blade.php as the index page which contains two forms for both signup and signin
This is how my UserController.php is set up:
namespace authme\Http\Controllers;
use Illuminate\Http\Request;
use authme\User;
use Illuminate\Support\Facades\Auth;
class UserController extends Controller
{
public function getDashboard()
{
return view('dashboard');
}
public function doSignUp(Request $request)
{
$this->validate($request, [
'email' => 'required|email|unique:users',
'first_name' => 'required|max:120',
'password' => 'required|min:6'
]);
$email = $request['email'];
$password = bcrypt($request['password']);
$first_name = $request['first_name'];
$last_name = $request['last_name'];
$location = $request['location'];
$phone = $request['phone'];
$user = new User();
$user->email = $email;
$user->password = $password;
$user->firstname = $first_name;
$user->lastname = $last_name;
$user->location = $location;
$user->phone = $phone;
$user->save();
Auth::login($user);
return redirect()->route('dashboard');
}
public function doSignIn(Request $request)
{
$this->validate($request, [
'email' => 'required',
'password' => 'required'
]);
if(Auth::attempt(['email' => $request['email'], 'password' => $request['password']])){
return redirect()->route('dashboard');
}
return redirect()->back();
}
}
To show the errors during signup/login, in my view file (welcome.blade.php), I've included:
#if(count($errors) > 0)
<div class="row">
<div class="alert alert-danger">
<ul>
#foreach($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
</div>
#endif
and the routes are set up like this:
Route::group(['middleware' => ['web']], function() {
Route::get('/', function () {
return view('welcome');
});
Route::post('/signup', [
'uses' => 'UserController#doSignUp',
'as' => 'signup'
]);
Route::post('/signin', [
'uses' => 'UserController#doSignIn',
'as' => 'signin'
]);
Route::get('/dashboard', [
'uses' => 'UserController#getDashboard',
'as' => 'dashboard'
]);
});
The forms are working fine when entering correct details. However when I enter incorrect data:
When I try to submit the blank form, it just redirects back to the original page, but no errors are shown
When I try to enter an email that is already in use, it again redirects back to the original page, but no errors are displayed
However, I couldn't find any possible syntax error in my code. Is there any logical errors?
PS:
I've not edited or modified App\Exceptions\Handler
None of the answers to questions asked both here and here solves my problem
If you're using Laravel version higher or equal to 5.2.25 you no longer need to put your routes in the web middleware. It is now automatically applied.
Putting your routes in the web middleware in the routes.php actually causes the problem.
Explained here.
You can also use following codes to show the errors for sign in with invalid credential.
public function doSignIn(Request $request)
{
$rules = array(
'email' => 'required',
'password' => 'required'
);
$validator = Validator::make($request->all(), $rules);
if ($validator->fails()){
return redirect('welcome')
->withErrors($validator)
->withInput();
}else{
if(Auth::attempt(['email' => $request['email'], 'password' => $request['password']])){
return redirect()->route('dashboard');
}
}
}
It seems to me your validation error messages are not getting saved to the session. Have a look at this.
https://github.com/laravel/framework/issues/12022
Related
I tried lot to search about the problem. I couldn't find any solution. Please help me to understand what i am doing wrong.
I am attaching the code:
UserController.php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
use Illuminate\Support\Facades\Auth;
class UserController extends Controller
{
public function signup(Request $request){
$this->validate($request,[
'name' => 'required',
'email' => 'required|unique:users',
'password' => 'required'
]);
$user = new User([
'name' => $request->input('name'),
'email' => $request->input('email'),
'password' => bcrypt($request->input('password ')),
]);
$user->save();
return response()->json([
'state' => 'success',
'message' => 'User created.'
],201);
}
public function signin(Request $request){
$credentials = $request->only('email', 'password');
dd(Auth::attempt($credentials));
if (!$token = $this->guard()->attempt($credentials)) {
return response()->json(['error' => 'Unauthorized'], 401);
}
return $this->respondWithToken($token);
}
}
And i have routes in api.php
Route::prefix('user')->group(function () {
Route::post('signup', 'UserController#signup');
Route::post('signin', 'UserController#signin');
});
I have
I have this in database
I sent the below json to signup first, but then when i sent to signin i am getting failed.
{
"name":"ironman",
"email":"ironman#yahoo.com",
"password":"avengers"
}
This is a brand new installation of laravel 5.4 (same with 5.5), Using detailt User migration and model came with it.
When i tried to diagnose the problem myself, i found that the password_very is returning false all the time in Auth package.
I am using default password field, hashing it while creating users as other similar questions answered.
I am using php artisan serv.
I am using postman to send this request.
Please help,
This is pulling null from the request:
$request->input('password '); // notice the space
'password' => bcrypt($request->input('password ')),
You probably did not intend to put a space at the end of the input name:
$request->input('password'); // no space
'password' => bcrypt($request->input('password')),
I am using use Illuminate\Http\Request to access form request. For example if my form request is coming from http://localhost:8012/test_project/public after validating it is automatically redirecting to http://localhost:8012/test_project/public with error messages but i want it to redirect to http://localhost:8012/test_project/public#myform because my form is visible in #myform section. So how can we do it. I am using Laravel 5.0
Following is my method code in controller that handles my request
public function add_user(Request $request){
$this->validate($request, [
'name' => 'required|min:3',
'email' => 'required|email|unique:users,email',
'mobile' => 'required|regex:/^[789]\d{9}+$/|unique:users,mobile',
'pass' => 'required|min:6',
'cpass' => 'required|same:pass'
]);
$user = new Myuser;
$user->name = $request->input('name');
$user->email = $request->input('email');
$user->mobile = $request->input('mobile');
$user->pass = md5("EEE".$request->input('pass'));
$user->register_on = date('Y-m-d');
$user->user_type = 'Free';
$user->last_login = date('Y-m-d H:i:s');
$user->status = 'Active';
$user->save();
$insertedId = $user->sno;
$uid = "UID".$insertedId;
Myuser::where('sno', $insertedId)
->update(['uid' => $uid]);
//echo $insertedId;
return redirect('')->with('message', 'Registered Successfully');
}
If you make your own Validator instead of using $this->validate(), you can have more control over what happens on a failed validation. Here is an example from the laravel documentation. Make sure you add use Validator; to the top of your php file. https://laravel.com/docs/5.3/validation
public function store(Request $request)
{
$validator = Validator::make($request->all(), [
'title' => 'required|unique:posts|max:255',
'body' => 'required',
]);
if ($validator->fails()) {
return redirect('post/create')
->withErrors($validator)
->withInput();
}
// Store the blog post...
}
i want to make an auto login after successful registration and redirect to Edit Profile page.. I tried the following code but not working as i want
class RegisterController extends Controller
{
use RegistersUsers;
protected $redirectTo = '/edit_profile';
public function __construct()
{
$this->middleware('guest');
}
public function createUser(Request $request)
{
$this->validate($request , [
'firstName' => 'required',
'lastName' => 'required',
'displayName' => 'required',
'email' => 'required |email',
'password' =>'required ',
'gender' =>'required',
'day' =>'required|max:2',
'month' =>'required|max:2',
'year' =>'required|max:4',
]);
$email=$request->input('email');
$password=$request->input('paasword');
$dob=$request->input('day').'-'.$request->input('month').'-'.$request->input('year');
$request->request->add(['dob'=>$dob]);
$request->request->add(['password'=>bcrypt($request->input('password'))]);
$data = User::create($request->except(['_token', 'submit', 'day','month','year', 'confirm_password' ,'dayInWeek']));
Auth::login($data);
}
}
Routes
Route::get('/', 'PageController#login');
Route::get('/home', 'HomeController#index');
Route::group( ['middleware' => 'auth' ], function()
{
Route::get('main', 'PageController#main');
Route::get('browse', 'PageController#browse');
Route::get('pickngo', 'PageController#pickngo');
Route::get('edit_profile', 'PageController#profile');
}
Use Laravel loginUsingId($id) function by passing the user id.
$data = User::create($request->except(['_token', 'submit', 'day','month','year', 'confirm_password' ,'dayInWeek']));
Auth::loginUsingId($data->id);
just modify your auth login just like
if(Auth::login($data)) {
return redirect('/edit_profile');
}
else
{
return redirect()->back();
}
Scren from documentation.
You just need to add after login redirectTo property or method inside your LoginController.
P.S.it will work if you're using laravel's make:auth.
I'm facing problem in my Laravel 5.3 custom auth want to use my own functions or pages when I check Auth::check() it returns false.
Here is User controller:
namespace App\Http\Controllers;
use App\User;
use Illuminate\Support\Facades\Session;
use validatior;
use Auth;
use Illuminate\Http\Request;
class UserController extends Controller
{
public function postSignUp(Request $request)
{
$validation = \Validator::make($request->all(), [
'email' => 'email|required|unique:users',
'password' => 'required|min:4'
]);
if ($validation->fails()) {
return redirect()->back()->withErrors($validation->errors());
} else {
$user = new User();
$user->email = $request->get("email");
$user->password = bcrypt($request->get['password']);
$user->save();
}
return redirect('signupPage');
}
public function postSignIn(Request $request)
{
$this->validate($request, [
'email' => 'required',
'password' => 'required',
]);
if (Auth::attempt(['email' => $request['email'], 'password' => $request['password']])) {
return redirect('users/profile');
}
dd(Auth::check());
exit;
}
}
After sign in I want to redirect at profile page but my condition is not working. My routes are:
Route::group(['prefix' => 'users'], function(){
Route::group(['middleware' => 'guest'], function(){
Route::get('/signupPage','UserController#getSignUp');
Route::post('/register',array ('as'=>'signup', 'uses' =>'UserController#postSignUp', ));
Route::get('signInPage', array('as' => 'signInPage', 'uses' => 'UserController#getSignIn'));
Route::post('/postLogin', array('as' => 'postLogin', 'uses' => 'UserController#postSignIn'));
});
Route::group(['middleware' => 'auth'], function(){
Route::get('/profile', array('as' => 'profile', 'uses' => 'UserController#getProfile'));
Route::get('/logout', array('as'=>'logout', 'uses'=> 'UserController#logout'));
});
});
Here are some Modifications of your code
public function postSignUp(Request $request)
{
$email = $request->input('email');
$pass = $request->input('password');
$validation = \Validator::make($request->all(), [
'email' => 'email|required|unique:users',
'password' => 'required|min:4'
]);
if ($validation->fails()) {
return redirect()->back()->withErrors($validation->errors());
} else {
$pas = bcrypt($pass);
$user = new User();
$user->email = $email;
$user->password = $pas;
$user->save();
}
return redirect('users/signInPage');
}
Do use bcrypt while registering your User as this function is by default used by Auth Attempt function
public function postSignIn(Request $request)
{
$this->validate($request, [
'email' => 'required',
'password' => 'required',
]);
$email= $request->input['email'];
$password= $request->input['password'];
if (Auth::attempt(['email'=>$email,'password'=>$password']))
{
return redirect('users/profile');
}
return redirect('users/signInPage')->withErrors(['failure' => 'The credentials you entered did not match our records. Try again!',]);
}
finally this will give you too many redirects error as you using default middlewares, because your logic is now differ from the default one that's why you have to write your custom middleware, for this run this command
php artisan make:middleware CutomAuth
this will create your custom middleware now write code in it by your logic and after registering in app/Http/Kernel.php as \n
'customauth' => \Illuminate\Auth\Middleware\CutomAuth::class, you are good to go
I'm getting this TokenMismatchException with Laravel 4.2.
TokenMismatchException will show up when I trying to post request.
For example Login Page.
If I submit that form TokenMismatchException will show up.
Is there any way I can validate all post request submitted ?
Here's the error :
Route::filter('csrf', function()
{
if (Session::token() != Input::get('_token'))
{
throw new Illuminate\Session\TokenMismatchException;
}
});
Here's my code :
route.php
Route::get('login',array('as' => 'login', 'uses' => 'AuthController#getLogin'))->before('guest');
Route::post('login',array('uses' => 'AuthController#postLogin'))->before('csrf');
Route::group(array('before' => 'auth'), function(){
Route::get('dashboard', array('as' => 'panel', 'uses' => 'DashboardController#view_dashboard'));
});
AuthController.php
class AuthController extends Controller {
public function getLogin(){
return View::make('users.login');
}
public function postLogin(){
$rules = array('username' => 'required', 'password' => 'required');
$validator = Validator::make(Input::all(), $rules);
if($validator->fails()){
return Redirect::route('login')->withErrors($validator);
}
$auth = Auth::attempt(array(
'username' => Input::get('username'),
'password' => Input::get('password')
), false);
if(!$auth){
return Redirect::route('login')->withErrors(array(
'Maaf anda bukan sebagai admin..'
));
}
//return "Success";
return Redirect::to('dashboard');
}
}
DashboardController.php
class DashboardController extends Controller {
public function view_dashboard(){
return View::make('dashboard.view_home_admin');
}
}
seems like you don't have hidden csrf field in your form.
try to add this in your form
{{ Form::token() }}