I'm trying to let someone register but when I click the register button I get 404 not found.
I've had this issue before but that was cuz of how the routes were ordered but as you can see I only have 2 in this project and the csrf is also implemented as required...
My form:
<!-- register form -->
<div class="col-md-6">
<h2>Register</h2>
<form method="post" action="{{ route('register') }}">
#csrf
<div class="form-group">
<label for="username">Your username</label>
<input type="text" class="form-control" name="username">
#if ($errors->has('username'))
<br><span class="text-danger">{{ $errors->first('username') }}</span>
#endif
</div>
<div class="form-group">
<label for="email">Your Email</label>
<input type="email" class="form-control" name="email">
#if ($errors->has('email'))
<br><span class="text-danger">{{ $errors->first('email') }}</span>
#endif
</div>
<div class="form-group">
<label for="password">Your password</label>
<input type="password" class="form-control" name="password">
#if ($errors->has('password'))
<br><span class="text-danger">{{ $errors->first('password') }}</span>
#endif
</div>
<div class="form-group">
<label for="repeat-password">Repeat your password</label>
<input type="password" class="form-control" name="repeat-password">
#if ($errors->has('repeat-password'))
<br><span class="text-danger">{{ $errors->first('repeat-password') }}</span>
#endif
</div>
<input type="submit" class="btn btn-primary" value="Register">
</form>
</div>
My web.php file with my routes:
<?php
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| 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!
|
*/
Route::get('/', 'PagesController#index')->name('home');
Route::post('/register', 'PagesController#register')->name('register');
This is my controller handling the functions:
<?php
namespace App\Http\Controllers;
use App\User;
use Illuminate\Http\Request;
use App\Http\Requests\RegistrationRequest;
class PagesController extends Controller
{
public function index() {
return view('pages.home');
}
public function register(RegistrationRequest $request) {
$user = new User;
$user->username = $request->input('username');
$user->email = $request->input('email');
$user->password = $request->bcrypt(input('password'));
$user->save();
session()->flash('status', 'Your account has been created!');
return Redirect::back();
}
}
Lastly the registration request:
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class RegistrationRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'name' => 'required|min:3|max:30',
'email' => 'email|unique:users',
'password' => 'required|confirmed|min:6'
];
}
}
So apperantly after installing the ui package all my custom routes stopped working. So starting a new project with the same code except the package works.
Related
Good day, I've been having a hard time solving this problem for almost a week now. I'm trying to login my Laravel project, the problem is it doesn't login even though the email and password (hashed in db) input is correct. Any help will be greatly appreciated. Below are the code of my files for LoginController.php, login.blade.php, and web.php
LoginController.php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Auth;
use DB;
use App\Models\Distributor;
use Carbon\Carbon;
use Session;
use Brian2694\Toastr\Facades\Toastr;
class LoginController extends Controller
{
/*
|--------------------------------------------------------------------------
| Login Controller
|--------------------------------------------------------------------------
|
| This controller handles authenticating users for the application and
| redirecting them to your home screen. The controller uses a trait
| to conveniently provide its functionality to your applications.
|
*/
use AuthenticatesUsers;
/**
* Where to redirect users after login.
*
* #var string
*/
protected $redirectTo = RouteServiceProvider::HOME;
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest')->except([
'logout',
'locked',
'unlock'
]);
}
public function login()
{
return view('auth.login');
}
public function username(){ return 'email_address';
}
public function authenticate(Request $request)
{
$request->validate([
'email' => 'required|string|email',
'password' => 'required|string',
]);
$email = $request->email;
$password = $request->password;
if (Auth::attempt(['emailAddress'=>$email,'password'=>$password,])) {
Toastr::success('Login successfully :)','Success');
return redirect()->intended('orders.sellload');
}elseif (Auth::attempt(['emailAddress'=>$email,'password'=>$password])) {
Toastr::success('Login successfully :)','Success');
return redirect()->intended('orders.sellload');
}elseif (Auth::attempt(['emailAddress'=>$email,'password'=>$password,])) {
Toastr::success('Login successfully :)','Success');
return redirect()->intended('admin.distributor');
}
elseif (Auth::attempt(['emailAddress'=>$email,'password'=>$password])) {
Toastr::success('Login successfully :)','Success');
return redirect()->intended('admin.distributor');
}else{
Toastr::error('fail, WRONG USERNAME OR PASSWORD :)','Error');
return redirect('login');
}
}
public function logout()
{
Auth::logout();
Toastr::success('Logout successfully :)','Success');
return redirect('login');
}
}
login.blade.php
#extends('layouts.app')
#section('content')
<div id="auth">
<div class="row h-100">
<div class="col-lg-3 col-12">
</div>
<div class="col-lg-6 col-12">
<div id="auth-left">
<p style="text-align:center;"><img src="assets/images/logo/icon.png" width="300" align>
</p>
{{-- message --}}
{!! Toastr::message() !!}
<p style="text-align:center;">Welcome to John Doe Portal</p>
#if(session()->has('error'))
<div class="text-danger text-center text-bold">
{{ session()->get('error') }}
</div>
#endif
<br>
<form method="POST" action="{{ route('login') }}" class="md-float-material">
#csrf
<div class="form-group position-relative has-icon-left mb-4">
<input type="text" class="form-control form-control-lg #error('email') is-invalid #enderror" name="email" value="{{ old('email') }}" placeholder="Enter email">
<div class="form-control-icon">
<i class="bi bi-person"></i>
</div>
#error('email')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
<div class="form-group position-relative has-icon-left mb-4">
<input type="password" class="form-control form-control-lg #error('password') is-invalid #enderror" name="password" placeholder="Enter Password">
<div class="form-control-icon">
<i class="bi bi-shield-lock"></i>
</div>
#error('password')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
<div class="form-check form-check-lg d-flex align-items-end">
<input class="form-check-input me-2" type="checkbox" value="remember_me" id="remember_me" name="remember_me">
<label class="form-check-label text-gray-600" for="flexCheckDefault">
Keep me logged in
</label>
</div>
<button class="btn btn-primary btn-block btn-lg shadow-lg mt-5">LOG IN</button>
</form>
</div>
</div>
<div class="col-lg-3 col-12">
</div>
</div>
</div>
#endsection
web.php
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\PhotosController;
use App\Http\Controllers\Auth\LoginController;
use App\Http\Controllers\Auth\RegisterController;
use App\Http\Controllers\ResetPasswordController;
use App\Http\Controllers\FormController;
use App\Http\Controllers\UserManagementController;
use App\Http\Controllers\LockScreen;
Route::get('/', function () {
return view('auth.login');
});
Route::get('/insert', function () {
$activationCodeParam=123456;
$idParentParam=1;
$tierParam=2;
$store = DB::select('
call createStore(?,?,?)',
array(activationCodeParam,idParentParam,tierParam));
});
Route::group(['middleware'=>'auth'],function()
{
Route::get('user',function()
{
return view('orders.sellload');
});
Route::get('home',function()
{
return view('orders.sellload');
});
});
Auth::routes();
Route::get('home',function()
{
return view('orders.sellload');
});
// ----------------------------- home dashboard ------------------------------//
Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])->name('home');
// -----------------------------login----------------------------------------//
Route::get('/login', [App\Http\Controllers\Auth\LoginController::class, 'login'])->name('login');
Route::post('/login', [App\Http\Controllers\Auth\LoginController::class, 'authenticate']);
Route::get('/logout', [App\Http\Controllers\Auth\LoginController::class, 'logout'])->name('logout');
You are missing the session refresh before your redirect.
// validation here
if(Auth::attempt(['emailAddress'=>$email,'password'=>$password,])) {
Toastr::success('Login successfully :)','Success');
$request->session()->regenerate(); // refresh session
return redirect()->intended('orders.sellload');
}
// …
This shouldn’t be related, but also your if-conditions don’t make sense — because they are all the same and if one matches, the other never can be reached.
Have you tried changing
if (Auth::attempt(['emailAddress'=>$email,'password'=>$password,]))
emailAddress
to email?
How can I make this reset password work without using a token and adding an email manually to reset password.
Like for example in the image I want to change the password to the email I added which is edgar.lozoya#ujed.mx
How can I make this reset password work without using a token and adding an email manually to reset password.
Like for example in the image I want to change the password to the email I added which is edgar.lozoya#ujed.mx
This is the reset.blade.php:
`#extends('layout.layout_reset')
#section('content')
<section class=" container section">
<h1 class="h2 text-center">
Restablecer contraseña
</h1>
#alert(['class' => 'alert--has-icon size-caption'])
#endalert
<div class="login-form ">
<base-form action="{{ url('contrasena/restablecer') }}"
inline-template
v-cloak
>
<form method="POST" class="form-boxed" action="{{ route('password.update') }}" >
#csrf
<text-field name="token" type="hidden" v-model="fields.token" maxlength="60" placeholder="" ></text-field>
<div class="form-control">
<label for="email">Correo electrónico</label>
<text-field name="email" type="email" v-model="fields.email" maxlength="60" value="{{ $email ?? old('email') }}" placeholder="" initial=""></text-field>
<field-errors name="email"></field-errors>
#error('email')
<span class="invalid-feedback" role="alert">
<strong>{{$message}}</strong>
</span>
#enderror
</div>
<div class="form-control">
<label for="password">Nueva contraseña</label>
<text-field name="password" type="password" v-model="fields.password" maxlength="60" placeholder="" initial=""></text-field>
<field-errors name="password"></field-errors>
#error('password')
<span class="invalid-feedback" role="alert">
<strong>{{$message}}</strong>
</span>
#enderror
</div>
<div class="form-control">
<label for="password_confirmation">Confirmar nueva contraseña</label>
<text-field name="password_confirmation" type="password" v-model="fields.password_confirmation" maxlength="60" placeholder="" initial=""></text-field>
<field-errors name="password_confirmation"></field-errors>
#error('password_confirmation')
<span class="invalid-feedback" role="alert">
<strong>{{$message}}</strong>
</span>
#enderror
</div>
<div class="text-center">
<form-button type="submit" class="btn--success w-full">
Enviar
</form-button>
</div>
</form>
</base-form>
<br>
<br>
<br>
<br>
</div>
</section>
#endsection
`
This is the reset password controller code:
`<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ResetsPasswords;
use App\User:
class ResetPasswordController extends Controller
{
/*
|--------------------------------------------------------------------------
| Password Reset Controller
|--------------------------------------------------------------------------
|
| This controller is responsible for handling password reset requests
| and uses a simple trait to include this behavior. You're free to
| explore this trait and override any methods you wish to tweak.
|
*/
use ResetsPasswords;
/**
* Where to redirect users after resetting their password.
*
* #var string
*/
protected $redirectTo = 'admin';
protected function redirectTo(){
if( Auth()->user()->role == 1){
return route('admin.dashboard');
}
elseif( Auth()->user()->role == 2){
return route('admin.dashboard');
}
}
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest');
}
public function showResetForm(Request $request, $token = null)
{
return view('auth.passwords.reset')->with(
['token' => $token, 'email' => $request->email]
);
}
}
these are the routes in the web.php fileRoute::post('passwords/reset', 'Auth\ResetPasswordController#reset')->name('password.update');
Route::post('auth/email', 'Auth\ForgotPasswordController#sendResetLinkEmail')->name('password.email'); `
I tried eliminating the token variables and requesting the email in the reset password controller
I am making a web app using Laravel 8, but my Authentication is being a little funky.
I created the Authentication using the php artisan ui:auth command.
Registration works fine: adding the new User to the database, logging in the user, redirecting to the home page.
The issue is that when I now try to login to that same user, the form just refreshes and doesn't log the user in.
Any help is much appreciated. Please let me know if you need more information!
Pertinent Code
web.php:
NOTE:
In PHPStorm, Auth is underlined as "undefined class Auth"
/adminregister is how I'm registering admin accounts for now.
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| 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!
|
*/
Route::get('/', function () {
return view('home');
});
Auth::routes();
Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])->name('home');
Route::get('/adminregister', function () {
return view('auth/adminregister');
});
Route::get('/getlocations', [App\Http\Controllers\LocationController::class, 'index']);
Route::post('/addlocation', [App\Http\Controllers\LocationController::class, 'store']);
User.php:
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* #var string[]
*/
protected $fillable = [
'username',
'password',
'role'
];
/**
* The attributes that should be hidden for serialization.
*
* #var array
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
public function locations()
{
return $this->hasMany(Location::class);
}
public function reviews()
{
return $this->hasMany(Review::class);
}
}
LoginController.php:
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
class LoginController extends Controller
{
/*
|--------------------------------------------------------------------------
| Login Controller
|--------------------------------------------------------------------------
|
| This controller handles authenticating users for the application and
| redirecting them to your home screen. The controller uses a trait
| to conveniently provide its functionality to your applications.
|
*/
use AuthenticatesUsers;
/**
* Where to redirect users after login.
*
* #var string
*/
protected $redirectTo = RouteServiceProvider::HOME;
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest')->except('logout');
}
}
login.blade.php:
#section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">{{ __('Login') }}</div>
<div class="card-body">
<form method="POST" action="{{ route('login') }}">
#csrf
<div class="form-group row">
<label for="username" class="col-md-4 col-form-label text-md-right">Username</label>
<div class="col-md-6">
<input id="username" type="text" class="form-control #error('username') is-invalid #enderror" name="username" value="{{ old('username') }}" required autocomplete="username" autofocus>
#error('username')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="form-group row">
<label for="password" class="col-md-4 col-form-label text-md-right">{{ __('Password') }}</label>
<div class="col-md-6">
<input id="password" type="password" class="form-control #error('password') is-invalid #enderror" name="password" required autocomplete="current-password">
#error('password')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="form-group row">
<div class="col-md-6 offset-md-4">
<div class="form-check">
<input class="form-check-input" type="checkbox" name="remember" id="remember" {{ old('remember') ? 'checked' : '' }}>
<label class="form-check-label" for="remember">
{{ __('Remember Me') }}
</label>
</div>
</div>
</div>
<div class="form-group row mb-0">
<div class="col-md-8 offset-md-4">
<button type="submit" class="btn btn-primary">
{{ __('Login') }}
</button>
#if (Route::has('password.request'))
<a class="btn btn-link" href="{{ route('password.request') }}">
{{ __('Forgot Your Password?') }}
</a>
#endif
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
#endsection
RegisterController.php:
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use App\Models\User;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
class RegisterController extends Controller
{
/*
|--------------------------------------------------------------------------
| Register Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users as well as their
| validation and creation. By default this controller uses a trait to
| provide this functionality without requiring any additional code.
|
*/
use RegistersUsers;
/**
* Where to redirect users after registration.
*
* #var string
*/
protected $redirectTo = RouteServiceProvider::HOME;
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest');
}
/**
* 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', 'string', 'max:255'],
'password' => ['required', 'string', 'min:8', 'confirmed'],
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return \App\Models\User
*/
protected function create(array $data)
{
return User::create([
'username' => $data['username'],
'password' => Hash::make($data['password']),
'role' => $data['role']
]);
}
}
register.blade.php
#section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">{{ __('Register') }}</div>
<div class="card-body">
<form method="POST" action="{{ route('register') }}">
#csrf
<div class="form-group row">
<input name="role" type="hidden" value="0">
<label for="username" class="col-md-4 col-form-label text-md-right">{{ __('Username') }}</label>
<div class="col-md-6">
<input id="username" type="text" class="form-control #error('username') is-invalid #enderror" name="username" value="{{ old('username') }}" required autocomplete="username" autofocus>
#error('username')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
{{-- <div class="form-group row">--}}
{{-- <label for="email" class="col-md-4 col-form-label text-md-right">{{ __('E-Mail Address') }}</label>--}}
{{-- <div class="col-md-6">--}}
{{-- <input id="email" type="email" class="form-control #error('email') is-invalid #enderror" name="email" value="{{ old('email') }}" required autocomplete="email">--}}
{{-- #error('email')--}}
{{-- <span class="invalid-feedback" role="alert">--}}
{{-- <strong>{{ $message }}</strong>--}}
{{-- </span>--}}
{{-- #enderror--}}
{{-- </div>--}}
{{-- </div>--}}
<div class="form-group row">
<label for="password" class="col-md-4 col-form-label text-md-right">{{ __('Password') }}</label>
<div class="col-md-6">
<input id="password" type="password" class="form-control #error('password') is-invalid #enderror" name="password" required autocomplete="new-password">
#error('password')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="form-group row">
<label for="password-confirm" class="col-md-4 col-form-label text-md-right">{{ __('Confirm Password') }}</label>
<div class="col-md-6">
<input id="password-confirm" type="password" class="form-control" name="password_confirmation" required autocomplete="new-password">
</div>
</div>
<div class="form-group row mb-0">
<div class="col-md-6 offset-md-4">
<button type="submit" class="btn btn-primary">
{{ __('Register') }}
</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
#endsection
User Migration:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('username')->unique();
$table->string('password');
$table->tinyInteger('role');
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('users');
}
}
Things I've Tried
Searched the web, and found a thread which seemed promising, but the solution was for a different version of the Authentication than I used: Laravel 5.2 login doesn't work, no redirect and no errors.
Adding a route that redirects back to home after reaching /login, but this wouldn't log in the user.
Deleting the migrations and re-running them using php artisan migrate:fresh.
A few other things that are slipping my mind now, but all to no avail.
By default, laravel use email for authentication but if you want to login with username (or something else). You need to override the username() method into the LoginController class. You don't need to change things in AuthenticatesUsers because, in my opinion, it's not a good thing to do that.
/**
* Get the login username to be used by the controller.
*
* #return string
*/
public function username()
{
return 'username';
}
Similarly, you can override other methods also, But instead, if you use email for your authentication then you don't need to do that.
I've observed that you're making use of username to login instead of email by default. Perhaps you can try changing the following under AuthenticatesUsers?
FROM
public function username()
{
return 'email';
}
TO
public function username()
{
return 'username';
}
When I try to login, it was working earlier, but now when I click on login it loads the same login page again. I am not sure what I am doing wrong.
Login.blade.php
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">{{ __('Login') }}</div>
<div class="card-body">
<form method="POST" action="{{ route('login') }}">
#csrf
<div class="form-group row">
<label for="email" class="col-md-4 col-form-label text-md-right">{{ __('E-Mail Address') }}</label>
<div class="col-md-6">
<input id="email" type="email" class="form-control #error('email') is-invalid #enderror" name="email" value="{{ old('email') }}" required autocomplete="email" autofocus>
#error('email')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="form-group row">
<label for="password" class="col-md-4 col-form-label text-md-right">{{ __('Password') }}</label>
<div class="col-md-6">
<input id="password" type="password" class="form-control #error('password') is-invalid #enderror" name="password" required autocomplete="current-password">
#error('password')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="form-group row">
<div class="col-md-6 offset-md-4">
<div class="form-check">
<input class="form-check-input" type="checkbox" name="remember" id="remember" {{ old('remember') ? 'checked' : '' }}>
<label class="form-check-label" for="remember">
{{ __('Remember Me') }}
</label>
</div>
</div>
</div>
<div class="form-group row mb-0">
<div class="col-md-8 offset-md-4">
<button type="submit" class="btn btn-primary">
{{ __('Login') }}
</button>
#if (Route::has('password.request'))
<a class="btn btn-link" href="{{ route('password.request') }}">
{{ __('Forgot Your Password?') }}
</a>
#endif
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
#endsection
RegisterController
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use App\User;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
class RegisterController extends Controller
{
/*
|--------------------------------------------------------------------------
| Register Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users as well as their
| validation and creation. By default this controller uses a trait to
| provide this functionality without requiring any additional code.
|
*/
use RegistersUsers;
/**
* Where to redirect users after registration.
*
* #var string
*/
protected $redirectTo = RouteServiceProvider::HOME;
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest');
}
/**
* 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', 'string', 'max:255', 'unique:users'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => ['required', 'string', 'min:8', 'confirmed'],
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return \App\User
*/
protected function create(array $data)
{
return User::create([
'username' => $data['username'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
}
}
LoginContainer
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
class LoginController extends Controller
{
/*
|--------------------------------------------------------------------------
| Login Controller
|--------------------------------------------------------------------------
|
| This controller handles authenticating users for the application and
| redirecting them to your home screen. The controller uses a trait
| to conveniently provide its functionality to your applications.
|
*/
use AuthenticatesUsers;
/**
* Where to redirect users after login.
*
* #var string
*/
protected $redirectTo = RouteServiceProvider::HOME;
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest')->except('logout');
}
}
web.php
<?php
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| 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!
|
*/
Route::get('/', function () {
return view('welcome');
});
Route::view('users','users');
Route::post('users','Users#index');
Auth::routes();
Route::get('/profile/{user}', 'ProfilesController#index')->name('profile.show');
Auth::routes();
Route::get('/home', 'HomeController#index')->name('home');
If any other code is required please let me know I will update my question. I am using laravel and sqlite as database, but it keep loading the same login page on login rather transferring to some different page
I believe you are being redirected because the validation is failing.
Enable error reporting in your .env file by changing APP_DEBUG=false to APP_DEBUG=true
You can as well include error messages in your blade to give you a better idea of what is wrong.
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
Also, ensure you include use App\User in your controller in case you are not using the default auth controller.
Lastly, you can share your controller here to make it easy for people to understand the issue and help you.
Cheers!
I have a problem with my validation in the login method.
Indeed, the problem is when I try to validate (with the validate method) my login by entering wrong login (I want to see the error messages) but the problem appears when it tries to redirect me back.
here is the login
view :
html :
<div class="container-fluid">
<div class="row justify-content-center">
<form method="POST" action="{{ route('login') }}" aria-label="{{ __('Login') }}">
<input type="hidden" name="_token" value="{{csrf_token()}}">
<div class="form-group row">
<label for="username" class="col-sm-4 col-form-label text-md-right">{{ __('E-Mail Address') }}</label>
<div class="col-md-6">
<input id="username" type="text" class="form-control{{ $errors->has('username') ? ' is-invalid' : '' }}" name="username" value="{{ old('username') }}" required autofocus>
#if ($errors->has('username'))
<span class="invalid-feedback" role="alert">
<strong>{{ $errors->first('username') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group row">
<label for="mdp" class="col-md-4 col-form-label text-md-right">{{ __('mot de passe') }}</label>
<div class="col-md-6">
<input id="mdp" type="password" class="form-control{{ $errors->has('mdp') ? ' is-invalid' : '' }}" name="mdp" required>
#if ($errors->has('mdp'))
<span class="invalid-feedback" role="alert">
<strong>{{ $errors->first('mdp') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group row">
<div class="col-md-6 offset-md-4">
<div class="form-check">
<input class="form-check-input" type="checkbox" name="remember" id="remember" {{ old('remember') ? 'checked' : '' }}>
<label class="form-check-label" for="remember">
{{ __('se souvenir de moi') }}
</label>
</div>
</div>
</div>
<div class="form-group row mb-0">
<div class="col-md-8 offset-md-4">
<button type="submit" class="btn btn-primary">
{{ __('Login') }}
</button>
<a class="btn btn-link" href="{{ route('password.request') }}">
{{ __('Forgot Your Password?') }}
</a>
</div>
</div>
</form>
</div>
</div>
Error :
the method of login :
class LoginController extends Controller
{
public function login(Request $request){
$this->validate($request, [
$this->username() => 'required|string|email|max:255',
'mdp' => 'required|string|min:6',
],$message);
if ($this->hasTooManyLoginAttempts($request)) {
$this->fireLockoutEvent($request);
return $this->sendLockoutResponse($request);
}
if ($this->attemptLogin($request)) {
return $this->sendLoginResponse($request);
}
$this->incrementLoginAttempts($request);
return $this->sendFailedLoginResponse($request);
}
}
the route :
Route::get('/', PATH_CENTRA_UTILISATEUR.'VerificationController#index')->name('verification_index');
Route::post('/verification',PATH_CENTRA_UTILISATEUR.'VerificationController#verifier')->name('verification_verifier');
Auth::routes();
And the list of route
You can help me, thank you all.
Your code is already mentioned in a Trait.
Please find below code.
LoginController.php
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use App\Http\Repository\RolePermissionRepository;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;
use Closure;
use Carbon\Carbon;
use Illuminate\Foundation\Application;
use Symfony\Component\HttpFoundation\Cookie;
use Illuminate\Contracts\Encryption\Encrypter;
use Illuminate\Session\TokenMismatchException;
use Illuminate\Support\Facades\Password;
use App\User;
use DB;
use Illuminate\Validation\ValidationException;
class LoginController extends Controller
{
/*
|--------------------------------------------------------------------------
| Login Controller
|--------------------------------------------------------------------------
|
| This controller handles authenticating users for the application and
| redirecting them to your home screen. The controller uses a trait
| to conveniently provide its functionality to your applications.
|
*/
use AuthenticatesUsers;
/**
* Where to redirect users after login.
*
* #var string
*/
protected $redirectTo = '/home';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct(Request $chekker)
{
// \Visitor::log(); //log in db visitor ip, geo location, hit counter
$this->middleware('guest')->except('logout');
}
}
This should solve your problem.
web.php
Auth::routes();
// please dont add this in any middleware
And check in this file vendor/laravel/framework/src/Illuminate/Routing/Router.php. => auth method if there are all routes are mentioned or not.
if nothing works. Please clear route cache and conf cache.
in worse case, try restarting your machine.
EDIT
Please see sample overriding of login method.
public function login(Request $request)
{
$remember = $request->has('remember');
$this->validateLogin($request);
if ($request->get('user_check') == '' || $request->get('user_check') == null) {
$checker = user::where("email",$request->email)->first();
if ($checker) {
//$this->checkInActive($request);
if (Auth::attempt(['email' => $checker->email, 'password' => $request->get('password'), 'id' => $checker->id] , $remember)) {
return redirect('/home');
} else {
return $this->sendFailedLoginResponse($request);
}
} else {
return $this->sendFailedLoginResponse($request);
}
}
}