Laravel 5 – login with username

  14/08/2015

With fresh Laravel 5 installation, you have authentication/register system out of the box ready for you (link).

By the default, login uses registered e-mail and password credentials. If you want to use username instead of e-mail, it’s no big deal. This modification works only for provided implemented Auth, and not for custom authentication.

After you install Laravel 5, you will find existing migration for users table in folder /migrations. To add username column, we need to modify it to look something like this, and that column needs to be unique same like email is. If you need more columns you can add them according to your needs. If there is no users table migration, you can easily create one with artisan: php artisan make:migration –create users create_users_table

Schema::create('users', function(Blueprint $table)
{
	$table->increments('id');
	$table->string('username')->unique();
	$table->string('email')->unique();
	$table->string('password', 60);
	$table->rememberToken();
	$table->timestamps();
});

Now you can run artisan and load migration file with php artisan migrate.

 

Next, we need to add username field in registration form, stored in /resources/views/auth/register.blade.php. If you use the default template, new input field should look something like:



 

Now let’s modify fillable protected variable in User model stored under /App/User.php, so it can be passed in array to the model itself (mass assignment). If you have more custom register fields, don’t forget to add them all here:

protected $fillable = ['username', 'email', 'password'];

 

User registration now goes through Registrar validator before creating new user. So, we have to change it to look like this (again, if you use more custom fields dont forget to add them here if they’re mandatory for registration and want them saved in database). File is located in /App/Services/Registrar.php.

namespace App\Services;

use App\User;
use Validator;
use Illuminate\Contracts\Auth\Registrar as RegistrarContract;

class Registrar implements RegistrarContract {

	/**
	 * Get a validator for an incoming registration request.
	 *
	 * @param  array  $data
	 * @return \Illuminate\Contracts\Validation\Validator
	 */
	public function validator(array $data)
	{
		return Validator::make($data, [
			'username' => 'required|max:255|unique:users',
			'email' => 'required|email|max:255|unique:users',
			'password' => 'required|confirmed|min:6',
		]);
	}

	/**
	 * Create a new user instance after a valid registration.
	 *
	 * @param  array  $data
	 * @return User
	 */
	public function create(array $data)
	{
		return User::create([
			'username' => $data['username'],
			'email' => $data['email'],
			'password' => bcrypt($data['password']),
		]);
	}

}

 

Now we have almost everything prepared. Login form has to be changed, so it asks for username instead of e-mail. In login blade file stored under /resources/views/auth/login.blade.php, modify it to look like this:

Before



After



 

One more thing and we’re done! Now, when we submit the form it sends the data to the Auth controller which uses implemented method postLogin(). We need to override it by adding the same method in /App/Http/Controllers/Auth/AuthController.php. We’re overriding the credentials check not to look for email, but username for validation. Just add this method, or modify it more if you need. I left the comment where you can put session flash_message commonly used in Laravel 5.


	/**
	 * Overriding postLogin() from Auth/AuthenticatesAndRegistersUsers
	 */
	public function postLogin(Request $request)
	{
		$this->validate($request, [
			'username' => 'required', 'password' => 'required',
		]);

		$credentials = $request->only('username', 'password');

		if ($this->auth->attempt($credentials, $request->has('remember')))
		{
			// You can add session flash_message here if you need
			return redirect()->intended($this->redirectPath());
		}

		return redirect($this->loginPath())
			->withInput($request->only('username', 'remember'))
			->withErrors([
				'username' => $this->getFailedLoginMessage(),
			]);
	}

 

Try it out. I hope this article was of help to someone 🙂


Weather Forecast – Belgrade

21/07
Fri
weather - icon
Rain
36°C
22/07
Sat
weather - icon
Rain
35°C
23/07
Sun
weather - icon
Clear
30°C
24/07
Mon
weather - icon
Rain
28°C
25/07
Tue
weather - icon
Rain
35°C
26/07
Wed
weather - icon
Rain
34°C
27/07
Thu
weather - icon
Rain
27°C

Powered by OpenWeatherMap | by Phee

RSS Laracasts

  • Auto-Registering Artisan Commands 20/07/2017
    In Laravel 5.5, you'll no longer be required to manually register your Artisan commands. The framework will instead automatically scan the commands folder for you. The means you may now run php artisan make:command FooCommand, and then immediately trigger it. Useful!
    Jeffrey Way
  • Instant Username Autocompletion: Part 2 18/07/2017
    Now that we understand how the At.js plugin works, we can begin integrating it into our forum. Let's get a working implementation setup in this episode. View the source code for this episode on GitHub.
    Jeffrey Way
  • Instant Username Autocompletion 17/07/2017
    In this episode, we'll begin researching how to allow for GitHub-style instant @username autocompletion. During the research phase, we'll set up a brand new throw-away project to learn how it will work. Then, once we feel comfortable, in the next episode we'll integrate autocompletion into our forum.
    Jeffrey Way
  • Vue and Turbolinks Sitting in a Tree 15/07/2017
    Vue is fantastic. Turbolinks is, too. So what if we could find a way to use them together seamlessly. Well, out of the box that can be a bit tricky, due to a few reactivity and caching issues. Luckily, though, this problem seems to have been solved. In this episode, come along as I test […]
    Jeffrey Way
  • What's New in Laravel Mix 14/07/2017
    Though Mix is entirely separate from Laravel 5.5, you will find a bump to version 1.0 in your package.json file. In this video, we'll review a few new additions, including updated versioning, sequential custom tasks, fast Sass compilation, CSS purification, and more.
    Jeffrey Way

Recent Posts

Contact