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

28/10
Wed
weather - icon
Clouds
16°C
29/10
Thu
weather - icon
Rain
15°C
30/10
Fri
weather - icon
Rain
13°C
31/10
Sat
weather - icon
Rain
14°C
01/11
Sun
weather - icon
Clear
10°C
02/11
Mon
weather - icon
Clear
12°C
03/11
Tue
weather - icon
Clear
11°C

Powered by OpenWeatherMap | by Phee

RSS Laracasts

  • Livewire File Uploads to Amazon S3 27/10/2020
    Many multi-tenant apps require image uploads, and may need to store those files in Amazon S3. Let’s create an Amazon S3 bucket from scratch and get it connected to our app. Then, we'll leverage the powerful and simple file uploading functionality that Livewire provides.
    Jeffrey Way
  • Upgrade the IGDB API to v4 23/10/2020
    This series used version 3 of the IGDB API; however, since publishing, version 4 is now available. In this supplementary episode, we'll review the necessary upgrade steps.
    Jeffrey Way
  • Use Livewire With Blade Components 23/10/2020
    It’s usually a good idea to extract reusable bits of code into Blade components. Let's set aside some time to extract a Livewire "text" input component and use whereStartsWith to get our wire:model attribute even when it includes a modifier.
    Jeffrey Way
  • Beware the Flying V Complication 22/10/2020
    A useful technique when refactoring code is to focus on confusing conditionals, long lines, and the "Flying V". In this episode, we'll review each of these as we spike out a fun, small example from scratch, and then proceed to refactor it line by line.
    Jeffrey Way
  • Telescope as a Monitoring App 20/10/2020
    Next, let's review how we might use Telescope to monitor an application in production.
    Jeffrey Way

Latest Tweets

  • Plasim se da bi vecina onih koji sada pljuju Srdjana Todorovica zbog raspalog pinka istog trenutka prihvatili posao… https://t.co/BlKZIyHoNM
    4 weeks ago
  • Jel neko prenosi jebenu Ligu Evrope?
    3 months ago
  • RT @nomen_est_omen7: HITNO POTREBNA KRV !!! Sveštenik Rajko Srdić je imao veliki moždani udar,u septičkom je stanju,dobio je koronu i na re…
    3 months ago