Laravel Jetstream: Login with Email, Username or Phone Number
Laravel Jetstream Authentication - Hi Coders, In this article I will share how to create a login feature with email, phone number or username in Laravel version 8. In this article, we will use a package to create an authentication feature in Laravel, namely the Jetstream package.
Why is it necessary to add a login option with a username or phone number? Usually, the email used by the user when registering, the text is too long and things like this are usually very difficult for the user to log in because they need to type in a long email. To solve this problem, we can add a login option with a username or with a user's phone number, which is usually not as long as an email and easier to remember.
Customizing User Authentication
- Step 1: Install Laravel
- Step 2: Install Jetstream
- Step 3: Setup Database
- Step 4: Update Migration File
- Step 5: Update User Model
- Step 6: Update Register Form
- Step 7: Update CreateNewUser.php
- Step 8: Update Login Form
- Step 9: Update Fortify Config
- Step 10: Update JetstreamServiceProvider.php
- Testing Login with Email, Username or Phone Number in Laravel 8
Okay, let's go straight to coding to create a login feature using email, username or phone number in laravel 8 and jetstream.✍ 👨💻
Step 1: Install Laravel
//via Laravel Installer
composer global require laravel/installer
laravel new laravel-jetstream-authentication
//via Composer
composer create-project laravel/laravel laravel-jetstream-authentication
In this first step, we need to install the latest version of laravel (currently version 8) which we will try to implement to create a login feature with email, username or phone number. For laravel installation, you can use the laravel installer or use composer like the example above.
Please choose one method you want to use for laravel installation. From the two examples of laravel installation commands above, they will both generate or generate a laravel project with the name laravel-jetstream-authentication.
Wait until the installation process is complete and when it's finished, don't forget to enter the project directory using the command cd laravel-jetstream-authentication.
Step 2: Install Jetstream
composer require laravel/jetstream
Before we can use jetstream in a this project to create a login feature with email, username or phone number with laravel 8 and jetstream livewire this time, we must first install jetstream. For that please run the command as above on the terminal to start installing jetstream.
php artisan jetstream:install livewire
After installing the jetstream package, we can run the command php artisan jetstream:install. The command accepts the stack we want (livewire or inertia). In addition, we can also add --teams to create a team management feature.
In this experimental project we will use jetstream with livewire. For that please run the command as above to install jetstream with livewire.
npm install && npm run dev
Next, we have to compile the assets that will be used by running the command as above.
Step 3: Setup Database
APP_NAME=Laravel
APP_ENV=local
APP_KEY=base64:bgyvD46KDF6+358Z6hP7UNHKMq4aIVlGAhnG9JLm1RI=
APP_DEBUG=true
APP_URL=http://127.0.0.1
LOG_CHANNEL=stack
LOG_LEVEL=debug
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_jetstream_authentication
DB_USERNAME=root
DB_PASSWORD=
Next, create a new database to experiment with creating a login feature with email, username or phone number with laravel 8 and jetstream livewire. If you are using xampp as a local development, please create a new database at localhost/phpmyadmin. Here I give an example, I created a new database with the name laravel_jetstream_authentication. Then don't forget to also adjust the DB_DATABASE in the .env file as in the example above.
Step 4: Update Migration File
<?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('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('username')->unique();
$table->string('phone')->unique();
$table->string('password');
$table->rememberToken();
$table->foreignId('current_team_id')->nullable();
$table->string('profile_photo_path', 2048)->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('users');
}
}
In this fourth step, we need to update the user migration file by adding two new fields namely username and phone. For that, please open the file in database/migrations/xxxx_xx_xx_xxxxxx_create_users_table.php, then add these two fields and so that the overall code in the user migration file will be like the code above.
Step 5: Update User Model
protected $fillable = [
'name',
'username',
'phone',
'email',
'password',
];
Next, open the User Model file and add username and phone in protected $fillable like the code above.
Step 6: Update Register Form
<div>
<x-jet-label for="username" value="{{ __('Username') }}" />
<x-jet-input id="username" class="block mt-1 w-full" type="text" name="username" :value="old('username')" required />
</div>
<div class="mt-4">
<x-jet-label for="phone" value="{{ __('Phone Number') }}" />
<x-jet-input id="phone" class="block mt-1 w-full" type="text" name="phone" :value="old('phone')" required />
</div>
In step six, we need to add two input fields for username and phone number on the register page or in the resources/views/auth/register.blade.php file. Add or copy the code above and paste it under the input field name.
Step 7: Update CreateNewUser.php
public function create(array $input)
{
Validator::make($input, [
'name' => ['required', 'string', 'max:255'],
'username' => ['required', 'string','max:255', 'unique:users'],
'phone' => ['required', 'string','max:255', 'unique:users'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => $this->passwordRules(),
'terms' => Jetstream::hasTermsAndPrivacyPolicyFeature() ? ['required', 'accepted'] : '',
])->validate();
return User::create([
'name' => $input['name'],
'username' => $input['username'],
'phone' => $input['phone'],
'email' => $input['email'],
'password' => Hash::make($input['password']),
]);
}
Okay, next we go to the seventh step. Open the file app/Actions/Fortify/CreateNewUser.php, then in the create method, add username and phone. So that the create method is now like the code above.
Step 8: Update Login Form
We continue to update the login form page or the files in resources/views/auth/login.blade.php. Look for the code as below, or the code for the email field.
<div>
<x-jet-label for="email" value="{{ __('Email') }}" />
<x-jet-input id="email" class="block mt-1 w-full" type="email" name="email" :value="old('email')" required autofocus />
</div>
Change the email input field code to be as below.
<div>
<x-jet-label for="auth" value="{{ __('Email/Username/Phone Number') }}" />
<x-jet-input id="auth" class="block mt-1 w-full" type="text" name="auth" :value="old('auth')" required autofocus />
</div>
Why do we change it? because our goal is to create a login feature with the option of using an email, username or phone number. The previous code can only be entered for the email type, and for the name we also change it to auth.
Step 9: Update Fortify Config
Since we changed the name in the input field in the login form, so we also need to update the config/fortify.php file. Look for code like below.
'username' => 'email',
Then change it to like below.
'username' => 'auth',
We replace it with auth because the name for the input field in the login form has been set to name="auth".
Step 10: Update JetstreamServiceProvider.php
In the last step, please open the app/Providers/JetstreamServiceProvider.php file and add the code as below. In this file, we add logic to create a login feature with options using email, username and phone number.
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Laravel\Fortify\Fortify;
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
// ...
Fortify::authenticateUsing(function (Request $request) {
$user = User::where('email', $request->auth)
->orWhere('username', $request->auth)
->orWhere('phone', $request->auth)
->first();
if ($user &&
Hash::check($request->password, $user->password)) {
return $user;
}
});
}
So the JetstreamServiceProvider.php file will be like below.
<?php
namespace App\Providers;
use App\Actions\Jetstream\DeleteUser;
use Illuminate\Support\ServiceProvider;
use Laravel\Jetstream\Jetstream;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Laravel\Fortify\Fortify;
class JetstreamServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*
* @return void
*/
public function register()
{
//
}
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
$this->configurePermissions();
Jetstream::deleteUsersUsing(DeleteUser::class);
Fortify::authenticateUsing(function (Request $request) {
$user = User::where('email', $request->auth)
->orWhere('username', $request->auth)
->orWhere('phone', $request->auth)
->first();
if ($user &&
Hash::check($request->password, $user->password)) {
return $user;
}
});
}
/**
* Configure the permissions that are available within the application.
*
* @return void
*/
protected function configurePermissions()
{
Jetstream::defaultApiTokenPermissions(['read']);
Jetstream::permissions([
'create',
'read',
'update',
'delete',
]);
}
}
Testing Login with Email, Username or Phone Number in Laravel 8
After going through the steps to create a login feature using email, username or phone number on laravel 8 and jetstream, starting from installing the latest version of laravel (currently version 8) to adding logic to login using email, username or phone number in the JetstreamServiceProvider file .php, now is the time to test the feature.
Please run the laravel project using the php artisan serve command, then open the laravel project in the browser. Navigate to the register menu and register a new user. After successfully registering, we will be directed to the dashboard page. After entering the dashboard page, please log out and try to login using the username and continue the login test using the phone number.
Finished. We have successfully created a login feature with the option of using email, username or phone number in laravel 8 and jetstream.
Until here, the tutorial article makes a login feature with the option of using email, username or phone number in laravel 8 and jetstream this time. You can explore the authentication feature on jestream with the link below.
Good luck, hopefully this article can be useful and see you in the next article.👋
Full Documentation: Laravel Jetstream Authentication
Credit: Mobile illustrations by Storyset
- Cara Mengatasi Error XAMPP: MySQL shutdown unexpectedly 23 Oktober 2021 65579 views
- Laravel 8: REST API Authentication dengan Sanctum 17 September 2021 31644 views
- Tutorial CRUD (Create, Read, Update & Delete) Codeigniter 4 dengan Bootstrap 14 Oktober 2021 29583 views
- Membuat REST API CRUD di Laravel 8 dengan Sanctum 18 September 2021 28216 views
- Contoh Cara Menggunakan Sweet Alert di Laravel 8 27 Agustus 2021 27270 views