Home > OS >  Register Logs User In, But Login Doesn't Laravel
Register Logs User In, But Login Doesn't Laravel

Time:11-17

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 hljs-string">">
                            <label for="username" hljs-number">4 col-form-label text-md-right">Username</label>

                            <div hljs-number">6">
                                <input id="username" type="text" hljs-built_in">error('username') is-invalid @enderror" name="username" value="{{ old('username') }}" required autocomplete="username" autofocus>

                                @error('username')
                                <span hljs-string">" role="alert">
                                        <strong>{{ $message }}</strong>
                                    </span>
                                @enderror
                            </div>
                        </div>

                        <div hljs-string">">
                            <label for="password" hljs-number">4 col-form-label text-md-right">{{ __('Password') }}</label>

                            <div hljs-number">6">
                                <input id="password" type="password" hljs-built_in">error('password') is-invalid @enderror" name="password" required autocomplete="current-password">

                                @error('password')
                                    <span hljs-string">" role="alert">
                                        <strong>{{ $message }}</strong>
                                    </span>
                                @enderror
                            </div>
                        </div>

                        <div hljs-string">">
                            <div hljs-number">6 offset-md-4">
                                <div hljs-string">">
                                    <input hljs-string">" type="checkbox" name="remember" id="remember" {{ old('remember') ? 'checked' : '' }}>

                                    <label hljs-string">" for="remember">
                                        {{ __('Remember Me') }}
                                    </label>
                                </div>
                            </div>
                        </div>

                        <div hljs-number">0">
                            <div hljs-number">8 offset-md-4">
                                <button type="submit" hljs-string">">
                                    {{ __('Login') }}
                                </button>

                                @if (Route::has('password.request'))
                                    <a hljs-string">" 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 hljs-string">">
                            <input name="role" type="hidden" value="0">
                            <label for="username" hljs-number">4 col-form-label text-md-right">{{ __('Username') }}</label>

                            <div hljs-number">6">
                                <input id="username" type="text" hljs-built_in">error('username') is-invalid @enderror" name="username" value="{{ old('username') }}" required autocomplete="username" autofocus>

                                @error('username')
                                    <span hljs-string">" role="alert">
                                        <strong>{{ $message }}</strong>
                                    </span>
                                @enderror
                            </div>
                        </div>

{{--                        <div hljs-string">">--}}
{{--                            <label for="email" hljs-number">4 col-form-label text-md-right">{{ __('E-Mail Address') }}</label>--}}

{{--                            <div hljs-number">6">--}}
{{--                                <input id="email" type="email" hljs-built_in">error('email') is-invalid @enderror" name="email" value="{{ old('email') }}" required autocomplete="email">--}}

{{--                                @error('email')--}}
{{--                                    <span hljs-string">" role="alert">--}}
{{--                                        <strong>{{ $message }}</strong>--}}
{{--                                    </span>--}}
{{--                                @enderror--}}
{{--                            </div>--}}
{{--                        </div>--}}

                        <div hljs-string">">
                            <label for="password" hljs-number">4 col-form-label text-md-right">{{ __('Password') }}</label>

                            <div hljs-number">6">
                                <input id="password" type="password" hljs-built_in">error('password') is-invalid @enderror" name="password" required autocomplete="new-password">

                                @error('password')
                                    <span hljs-string">" role="alert">
                                        <strong>{{ $message }}</strong>
                                    </span>
                                @enderror
                            </div>
                        </div>

                        <div hljs-string">">
                            <label for="password-confirm" hljs-number">4 col-form-label text-md-right">{{ __('Confirm Password') }}</label>

                            <div hljs-number">6">
                                <input id="password-confirm" type="password" hljs-string">" name="password_confirmation" required autocomplete="new-password">
                            </div>
                        </div>

                        <div hljs-number">0">
                            <div hljs-number">6 offset-md-4">
                                <button type="submit" hljs-string">">
                                    {{ __('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.

CodePudding user response:

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';
    }

CodePudding user response:

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.

  • Related