Sunday, February 10, 2019

Integrating The Default Authentication of Laravel with Current App

Integrating The Default Authentication of Laravel with Current App
The authentication is nearly necessary in every application. The Default Authentication in Laravel is simple to create yet powerful. It save a lot of time and effort of developers. It can be integrated into the current app with minor modifications.
Here are the key steps to do so:

1. Add two fields to users table

Let’s say there are table fields, ‘birthday’ and ‘is_admin’, need to be added to the table users. We can make a migration file first:
>php artisan make:migration add_fields_to_users_table --table=users
Created Migration: 2019_02_08_134603_add_fields_to_users_table
Secondly, we need to add codes to the migration file ‘2019_xx_xx_xxxxxx_add_fields_to_users_table.php’ under database/migrations directory.
public function up()
{
  Schema::table('users', function (Blueprint $table) {
  //
    $table->date('birthday')->nullable()->after('remember_token');
    $table->boolean('is_admin')->default(false)->after('birthday');
  });
}

public function down()
{
  Schema::table('users', function (Blueprint $table) {
  //
    $table->dropColumn('birthday');
    $table->dropColumn('is_admin');
  });
}
Thirdly, Execute php artisan migrate to add table fields to table users.
> php artisan migrate
Migrating: 2019_02_08_134603_add_fields_to_users_table
Migrated:  2019_02_08_134603_add_fields_to_users_table
Then we can make a commit to the git repository.
After executing php artisan make:auth and authentication file generation, a layout file has been generated:
resources/views/layouts/app.blade.php
This is the default layout page. It is shared by all Auth view file. We can find the code of ‘Login’ and ‘Register’ link in the file:
<!-- Authentication Links -->
@guest
  <li class="nav-item">
    <a class="nav-link" href="{{ route('login') }}">{{ __('Login') }}</a>
  </li>
  @if (Route::has('register'))
    <li class="nav-item">
      <a class="nav-link" href="{{ route('register') }}">{{ __('Register') }}</a>
    </li>
  @endif
@else
  <li class="nav-item dropdown">
    <a id="navbarDropdown" class="nav-link dropdown-toggle" href="#" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" v-pre>
      {{ Auth::user()->name }} <span class="caret"></span>
    </a>
    <div class="dropdown-menu dropdown-menu-right" aria-labelledby="navbarDropdown" 
      <a class="dropdown-item" href="{{ route('logout') }}" 
         onclick="event.preventDefault();document.getElementById('logout-form').submit();">
         {{ __('Logout') }}
      </a>
      <form id="logout-form" action="{{ route('logout') }}" method="POST" style="display: none;">
         @csrf
      </form>
    </div>
  </li>
@endguest
For the integration of all views ( current and Auth generated ), all we have to do is to:
  1. Copy the layout file we prefer to the directory resources/views/layouts/
  2. Rename it to app.blade.php. (rename original app.blade.php to other name first.)
  3. Insert the the code of ‘Login’ and ‘Register’ link above at the navbar position of the file.
  4. Update the @extends('layout') in all view file to @extends('layouts.app') to ensure all view files point to the same default layout file.
  5. The Auth view files are no need to changed.
enter image description here

3. Edit attributes of Model User

There are attributes ('birthday' and 'is_admin') of model User need to be added in app/User.php.
protected $fillable = [
   'name', 'email', 'password', 'birthday', 'is_admin'];

4. Modification of controller

For the controller, we need to add attributes 'birthday' and 'is_admin' to the file
App/Http/Controllers/Auth/RegisterController.php
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:6', 'confirmed'],
    'birthday' => ['date','nullable'],
    'is_admin' => ['boolean'],
    ]);
}

protected function create(array $data)
{
  $is_admin = array_key_exists('is_admin', $data) ? true : false;
  return User::create([
    'name' => $data['name'],
    'email' => $data['email'],
    'password' => Hash::make($data['password']),
    'birthday' => $data['birthday'],
    'is_admin' => $is_admin',
  ]);
}

5. Add the fields to the view file

Now, 'birthday'and 'is_admin' have to be added to the user register page at resources/views/auth/register.blade.php
For 'birthday':
<div class="form-group row">
  <label for="birthday" class="col-md-4 col-form-label text-md-right">{{ __('Birthday') }}</label>
  <div class="col-md-6">
    <input id="birthday" type="date" class="form-control{{ $errors->has('birthday') ? ' is-invalid' : '' }}" 
      name="birthday" value="{{ old('birthday') }}">
    
    @if ($errors->has('birthday'))
      <span class="invalid-feedback" role="alert">
        <strong>{{ $errors->first('birthday') }}</strong>
      </span>
    @endif
  </div>
</div>
For ‘is_admin’:
<div class="form-group row">
  <label for="is_admin" class="col-md-4 col-form-label text-md-right">{{ __('Administrator?') } </label>
  <div class="col-md-6">
    <input id="is_admin" type="checkbox" class="
form-control{{ $errors->has('is_admin') ? ' 
is-invalid' : '' }}" name="is_admin" value="1">
    @if ($errors->has('is_admin'))
      <span class="invalid-feedback" role="alert">
        <strong>{{ $errors->first('is_admin') }}</
strong>
      </span>
    @endif
  </div>  
</div>
The register form is similar like:
enter image description here

6. Note: Checkbox Behavior

Unlike other input controls, a checkbox value is only included in the submitted data if the checkbox is currently checked. If it is, then the value of the checkbox’s valueattribute is reported as the input’s value.
If the checkbox is unchecked, both the key and value of the checkbox are NOT submitted. It submits nothing.
Therefore, the value of the checkbox ‘is_admin’ is set to ‘1’ for representing ‘true’ boolean value. It will be validated by the validator of RegisterController when submitted.
'is_admin'  =>  ['boolean']
Then in the create function of the RegisterController, the 'is_admin' key is checked whether it exists in the array $data . If does, it means the 'is_admin' is true, otherwise false.
$is_admin = array_key_exists('is_admin', $data) ? true : false;
return User::create([
    'name' => $data['name'],
    'email' => $data['email'],
    'password' => Hash::make($data['password']),
    'birthday' => $data['birthday'],
    'is_admin' => $is_admin',

1 comment:

  1. JackpotCity Casino Review 2021 - A Pro Guide - Poormans
    JackpotCity 블랙 벳 Casino Review 한게임 포커 2021 ➤ Find out everything you need to know about JackpotCity Casino 바카라추천사이트 from the 유흥업소사이트 experts 포커 규칙 here.

    ReplyDelete