Introduction to PHP framework "Laravel"

Introduction to PHP framework “Laravel”

In addition to the convenient commands introduced so far, Laravel has functions related to authentication and authorization that are indispensable for creating Web applications from the beginning.One of them is the “login function” that allows only registered users to view and use Web applications . The login function is indispensable for membership-based web applications. Other than that, it is useful when you want to create an administrator user and perform operations on the Web that general users cannot do.It is a login function that takes 1 to 2 days if you make it from scratch, but Laravel has it from the beginning, so it has the advantage that it can be introduced in a minimum of 10 minutes.It’s easy to customize and very convenient, so please take advantage of it.

table of contents

Login function 1.1 Enable login function 1.2 Login screen 1.3 User registration screen Customization of login function 2.1 Japanese localization of login form and user registration form 2.2 Enable to log in with user ID 2.3 Add items to user registration screen Finally

1. Login function

The login function provided by Laravel from the beginning is as simple as entering the user’s email address and password. If the email address you entered exists in the Users table of the database and the passwords match, the login will be successful. Developers can set up pages that only users who have successfully logged in can see, buttons that can be pressed, and so on.This alone is functionally sufficient, but it can be customized to make it even easier to use. The customization method will be described later, so let’s first enable the login function with the default settings.

1.1 Enabling the login function

To enable Laravel’s login feature, run the Artisan make: auth command.Move to #Laravel project (PROJECT_NAME) cd ~ / html / laravel / PROJECT_NAME #Enable login function Php – 7.1 Artisan Make : Auth Authentication scaffolding generated successfully.Is displayed, the command is successful. Surprisingly, this alone adds the files needed for the login feature to your project.* If the User table has not been created in the database yet, an error will occur, so please execute the database migration first.php-7.1 artisan migrate- 7.1 Artisan Migrate In order to immediately reflect the generated login function related classes in the Web application, execute the cache clear with the following command.php-7.1 artisan clear-compiled- 7.1 Artisan Clear – Compiled Php – 7.1 Artisan Optimize Php – 7.1 Artisan View : Clear After running artisan optimize, the following error message is displayed, but you can safely ignore it.LogicException: Unable to prepare route [api / user] for serialization. Uses Closure. : Unable to prepare route [ api / user ] for serialization . Uses Closure . When you access the top page of the Web application after executing the cache clear, you can see that the buttons “LOGIN” and “REGISTER” are added to the header part .http: // <public URL of the server> / laravel / PROJECT_NAME / public /width =

1.2 Login screen

Click “LOGIN” added to the header part to display the login screen.width =E-Mail Address: User’s e-mail address Password: Password If you check Remember Me and log in, the login information will be recorded in the browser and the next login will be omitted. Forgot Your Password? Is a function to send a password reset link by e-mail when the user forgets the password. This is also prepared from the beginning, so it is very convenient.

1.3 User registration screen

Click “REGISTER” added to the header part to display the user registration screen. The user first registers his / her user information (authentication information) on this screen.width =For Name, enter the user ID desired by the user. For E-Mail Address, the user enters his / her own e-mail address. For Password, enter the password that the user wants to enter when logging in. Confirm Password is to prevent erroneous input, and enter the desired password again.The user information (authentication information) handled by the Laravel login function by default is as described above. If you want to increase other items, please refer to the customization method described later.Let’s actually register a test user.width =If the same email address is already registered, an error message will be displayed. When creating multiple test users, please use a different email address for each user.If the user registration is successful, you will be automatically taken to the dashboard page.width =Click Logout in the header menu to log out and return to the top page.

2. Customize login function

In the previous chapter, we explained how to introduce the login function of Laravel. It works well in its default state, but it is easier to use and can be customized to suit the intended use of your web application.Here are some examples of customization, so if you have something you would like to introduce to your own web application, please refer to the procedure and introduce it.2.1 Japanese localization of login form and user registration form All items on the login form and user registration form are written in English. If it is left as it is, it will be unfriendly to the user, so I will change it to Japanese.First, change the input form on the login screen to Japanese.resources / views / auth / login.blade.phpextends (‘layouts.app’)( ‘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” > email 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>strong > </ </ strong>span > @enderror </ </ strong>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” > Save login information </ strong > 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’)}}” > Did you forget your password? </ a > @endif </ </ strong>div > </ </ strong>div > </ </ strong> form > </ </ strong>div > </ </ strong>div > </ </ strong>div > </ div > </ </ strong>div > @endsection Next, change the input form on the user registration screen to Japanese.resources / views / auth / register.blade.phpextends (‘layouts.app’)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” > {{ __ ( ‘Register’ ) }} </ div > < div class = “card-body”> < form method = “POST” action = “{{route (‘register’)}}” > @csrf < div class = “form-group row”> < label for = “name” class = “col-md-4 col-form-label text-md-right” > Desired user ID </ label > < div class = “col-md-6”> < input id = “name” type = “text” class = “form-control @error (‘name’) is-invalid @enderror” name = “name” value = “{{old (‘name’)}}” required autocomplete = “name” autofocus > @error ( ‘name’ ) < span class = “invalid-feedback” role = “alert”> <strong> {{ $ message }} </ strong>strong > </ </ strong>span > @enderror </ div> </ div > < div class = “form-group row”> < label for = “email” class = “col-md-4 col-form-label text-md-right” > email 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” > Password (please enter again for confirmation) </ 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

2.2 Allow users to log in with their user ID

By default, Laravel’s login function authenticates with a combination of email address and password. If this is the case, it will be troublesome to enter if the email address is long , so customize it so that you can log in with your user ID and password .First, add the following description to the login function controller.app / Http / Controllers / Auth / LoginController.php<? phpphp namespace App \ Http \ Controllers \ Auth ; use App \ Http \ Controllers \ Controller ; use Illuminate \ Foundation \ Auth \ AuthenticatesUsers ; use Illuminate \ Http \ Request ; class LoginController extends Controller {use AuthenticatesUsers ; / ** * Where to redirect users after login. * * @var string * / protected $ redirectTo = ‘/ home’ ;/ ** * Create a new controller instance. * * @return void * / public function __construct () { $ this- > middleware ( ‘guest’ )-> except ( ‘logout’ ); }public function username () { return’name ‘ ; } } Add a function called username and specify the name of the column you want to use for login (name because it is a user ID this time) as a character string in the return value.Next, change the screen items on the login screen.resources / views / auth / login.blade.php@extends (‘layouts.app’)( ‘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 <!-Comment out the input items of the email address- > < div class = “form-group row” > < label for = “email” class = “col-md-4 col-form-label text-md-right” > email 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 > -> <!- Add a new user ID input item- > < div class = “form-group row” > < label for = “name” class = “col-md-4 col-form-label text-md-right” > User ID </ label > < div class = “col-md-6” > < input id = “name” type = “text” class = “form-control @error (‘name’) is-invalid @enderror” name = “name” value = “{{old (‘name’)}}” required autocomplete = “name” autofocus > @error ( ‘name’ ) < span class = “invalid-feedback” role = “alert” > <strong> {{ $ message }} </ strong > </ span > @enderror </ div > </ div > ~ Abbreviation ~ Delete the email address input form from the login screen input form. (This time, I commented it out for clarity.) Instead, I added a new user ID input form (input name = “name”).This will change the item used for login from your email address to your user ID.

2.3 Add items to the user registration screen

Finally, how to add your own items such as name, address, and phone number to the user registration screen.It’s a little complicated, but in actual Web applications, this information is often registered when you register as a member, so please remember and use it.

2.3.1 Add column for Users table

First, create a migration file in the Users table to increase the name and phone number columns.php-7.1 artisan make: migration update_user_table –table = users- 7.1 Artisan Make : Migration Update_user_table – Table = Users database / migrations / date_update_user_table.php<? phpphp use Illuminate \ Support \ Facades \ Schema ; use Illuminate \ Database \ Schema \ Blueprint ; use Illuminate \ Database \ Migrations \ Migration ; class UpdateUserTable extends Migration { / ** * Run the migrations. * * @return void * / public function up () { Schema :: table ( ‘users’ , function ( Blueprint $ table ) { $ table- > string ( ‘fullname’ ); // Add name column $ table- > string ( ‘phone’ ); // Add phone number column }); } / ** * Reverse the migrations. * * @return void * / public function down () { Schema :: table ( ‘users’ , function ( Blueprint $ table ) { }); } } After creating the migration file, execute the migration.php-7.1 artisan migrate- 7.1 Artisan Migrate If successful, the “fullname” and “phone” columns will be added to the Users table on the database.width =2.3.2 User model changes Next, change the contents of the User model according to the changes in the table.app / User.php<? phpphp namespace App ; use Illuminate \ Notifications \ Notifiable ; use Illuminate \ Contracts \ Auth \ MustVerifyEmail ; use Illuminate \ Foundation \ Auth \ User as Authenticatable ; class User extends Authenticatable { use Notifiable ; / ** * The attributes that are mass assignable. * * @var array * / protected $ fillable = [ ‘name’ , ’email’ , ‘password’ ,’ fullname ‘,’ phone ‘, ];; / ** * The attributes that should be hidden for arrays. * * @var array * / protected $ hidden = [ ‘password’ , ‘remember_token’ , ];; / ** * The attributes that should be cast to native types. * * @var array * / protected $ casts = [ ’email_verified_at’ => ‘datetime’ , ];; } The newly added column names “fullname” and “phone” are added to the $ fillable array of fields.Please note that if you forget to change this, you will get an error when registering the entered name and phone number in the Users table.

2.3.3 Change of input form

Next, add the name and phone number items to the input form on the user registration screen.resources / views / auth / register.blade.php@extends (‘layouts.app’)( ‘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” > {{ __ ( ‘Register’ ) }} </ div > < div class = “card-body” > < form method = “POST” action = “{{route (‘register’)}}” > @csrf ~ Abbreviation ~ < div class = “form-group row” > < label for = “fullname” class = “col-md-4 col-form-label text-md-right” > Name </ label > < div class = “col-md-6” > < input id = “fullname” type = “text” class = “form-control @error (‘fullname’) is-invalid @enderror” name = “fullname” value = “{{old (‘fullname’)}}” required > @error ( ‘fullname’ ) < span class = “invalid-feedback” role = “alert” > <strong> {{ $ message }} </ strong > </ span > @enderror </ div > </ div >< div class = “form-group row” > < label for = “phone” class = “col-md-4 col-form-label text-md-right” > phone number </ label > < div class = “col-md-6” > < input id = “phone” type = “text” class = “form-control @error (‘phone’) is-invalid @enderror” name = “phone” value = “{{old (‘phone’)}}” required > @error ( ‘phone’ ) < span class = “invalid-feedback” role = “alert” > <strong> {{ $ message }} </ strong > </ span > @enderror </ div > </ div >~ Abbreviation ~

2.3.4 Controller changes

Finally, add the validation rule (validation rule) and registration process of the new item to the controller file for user creation.app / Http / Controllers / Auth / RegisterController.php<? phpphp namespace App \ Http \ Controllers \ Auth ; use App \ User ; use App \ Http \ Controllers \ Controller ; use Illuminate \ Support \ Facades \ Hash ; use Illuminate \ Support \ Facades \ Validator ; use Illuminate \ Foundation \ Auth \ RegistersUsers ; class RegisterController extends Controller { use RegistersUsers ; / ** * Where to redirect users after registration. * * @var string * / protected $ redirectTo = ‘/ 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 , [ ‘name’ => [ ‘required’ , ‘string’ , ‘max: 255′ ], ’email’ => [ ‘required’ , ‘string’ , ’email’ , ‘max: 255’ , ‘unique: users’ ], ‘password’ => [ ‘required’ , ‘string’ , ‘min: 8’ , ‘confirmed’ ], ‘fullname’ => [ ‘required’ , ‘string’ , ‘max: 255’ ], ‘phone’ => [ ‘required’ , ‘string’ , ‘max: 50’ ], ]); } / ** * Create a new user instance after a valid registration. * * @param array $ data * @return \ App \ User * / protected function create ( array $ data ) { return User :: create ([[ ‘name’ => $ data [ ‘name’ ], ’email’ => $ data [ ’email’ ], ‘password’ => Hash :: make ( $ data [ ‘password’ ]), ‘fullname’ => $ data [ ‘fullname’ ], ‘phone’ => $ data [ ‘phone’ ], ]); } } Validator :: make set in the return value of the validator function describes what kind of check is performed for each input item.I will omit the explanation of detailed validation rules, but if you set required, you will be required to enter it. On the contrary, if nothing is defined, it will be an optional input item.We are registering in the Users table with User :: create of the create function. Add the name and phone number substitution process here.

2.3.5 Registration and confirmation of user information

This completes the procedure for customizing additional items on the user registration form.Now, let’s actually register.width =After registration is complete, display the newly added name and phone number on the dashboard screen to check if registration is correct.resources / views / home.blade.php@extends (‘layouts.app’)( ‘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” > Dashboard </ div > < div class = “card-body” > @if ( session ( ‘status’ )) < div class = “alert alert-success” role = “alert” > {{ session ( ‘status’ ) }} </ div > @endif <h2> Welcome, {{ Auth :: user ()-> fullname }}! </ h2 > <h3> Contact: <a href = “tel: {{Auth :: user ()-> phone}}” > {{ Auth :: user ()-> phone }} < / a> </ h3 ></ div > </ div > </ div > </ div > </ div > @endsection Information about the logged-in user can be called with Auth :: user.width =If the name and phone number are displayed as shown in the image, the customization is successful.

3. Finally

This time, we introduced the login function among the authentication / authorization functions of Laravel .The login function is indispensable for creating web applications, so please make full use of Laravel’s login function to speed up development.There are many customization methods other than those introduced here, so please find the most suitable customization method for the web application you want to create.