Thứ Tư, 12 tháng 10, 2016

laravel 5 tutorial : User Authentication with Ajax Validation in laravel 5.3


Laravel 5.3 tutorial - Working with Ajax, we can create User Authentication with Ajax Validation, At the previews tutorial, we have learn how to crate User authentication in laravel 5.3, please read for more detail here.

How to add Ajax form validation to Laravel User Authentication that is generated by the Artisan console.

User Authentication with Ajax Validation

First step, we will create new database named with "authentication_db" or anything you want, and next crate new Laravel project using composer, please read How to Install laravel.

User Authentication with Ajax Validation in laravel 5.3

Create Laravel Project

cd c:\xampp\htdocs
......
composer create-project --prefer-dist laravel/laravel hckr

"hckr" is our project name, you change it with another name.

After finished, open your project with Text Editor (i'm using Atom Tex Editor).

Create Connection

Configuration our project to connect to database, Open your .ENV file and configuration with yours.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=hckr_db
DB_USERNAME=root
DB_PASSWORD=yourpassword

Generate Authentication

Create default authentication from laravel following by this Artisan Comamand.

php artisan make:auth

Now the Laravel site has routes and views to allow a user to register, login, logout, and reset their password. A HomeController has also been added to allow authenticated users to enter its view.

Database Migration

To migrate our "users" table run migration following by this command

php artisan migrate

User Model

Next create a folder named with "Models" in the app directory and then move the User.php model into app/Models/.
or you can run this command

mkdir app/Models
....
mv app/User.php app/Models

Next, we need to update the App namespace to App\Models. And adding the public function rules() to the class.

<?php
namespace App\Models;
use Illuminate\Notifications\Notifiable;
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',
    ];
    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];
    public function rules(){
      return [
        'name' => 'required|max:255',
        'email' => 'required|email|max:255|unique:users',
        'password' => 'required|min:6|confirmed',
      ];
    }
}

Registration Controller

Locate the validator function and replace the array of rules being passed to the Validator make method with a call to the newly created rules method in our User model.

<?php

namespace App\Http\Controllers\Auth;

use App\Models\User;
use Validator;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\Registers\Users;

class RegisterController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Register Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles the registration of new users as well as their
    | validation and creation. By default this controller uses a trait to
    | provide this functionality without requiring any additional code.
    |
    */

    use RegistersUsers;

    /**
     * Where to redirect users after login / 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 IlluminateContractsValidationValidator
     */
    protected function validator(array $data)
    {
        return Validator::make($data, (new User)->rules());
    }

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

Config/Auth.php

Edit, config/auth.php, update the authentication drivers user provider.

'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => AppModelsUser::class,
        ],

        // 'users' => [
        //     'driver' => 'database',
        //     'table' => 'users',
        // ],
    ],

User Validation Controller

Create a new Validation folder in Controllers following by this command.

mkdir app/Http/Controllers/Validation

Create a new controller: app/Http/Controllers/Validation/UserController.php in the new Validation folder. It has a single method that applies the rules from the User model for validation.

<?php
namespace App\Http\Controllers\Validation;
use App\Models\User;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Http\Requests;
class UserController extends Controller
{
   public function user(Request $request){
     $this->validate($request, (new User)->rules());
   }
}

Routes (Routes/web.php)

Create new route into routes/web.php file to register a route group using api middleware. Inside this group add a validate/user route that accepts a POST method. The request is then sent to the new Validation\UserController user method for validation.

<?php

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| This file is where you may define all of the routes that are handled
| by your application. Just tell Laravel the URIs it should respond
| to using a Closure or controller method. Build something great!
|
*/

Route::get('/', function () {
    return view('welcome');
});

Route::group(['middleware' => ['api']], function () {
    Route::post('validate/user',[
      'uses' => 'ValidationUserController@user',
    ]);
});

Auth::routes();

Route::get('/home', 'HomeController@index');

Register Form Template

Edit the user registration form template, That stored on resources/views/auth/register.blade.php. Remove all the blade if statements that surround the span help blocks. Each of these blocks need to be rendered by the server and made available to the javascript to display any errors.

This full source code from register.blade.php

@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row">
        <div class="col-md-8 col-md-offset-2">
            <div class="panel panel-default">
                <div class="panel-heading">Register</div>
                <div class="panel-body">
                    <form class="form-horizontal" role="form" method="POST" action="{{ url('/register') }}">
                        {{ csrf_field() }}

                        <div class="form-group{{ $errors->has('name') ? ' has-error' : '' }}">
                            <label for="name" class="col-md-4 control-label">Name</label>

                            <div class="col-md-6">
                                <input id="name" type="text" class="form-control" name="name" value="{{ old('name') }}" required autofocus>

                                    <span class="help-block">
                                        <strong>{{ $errors->first('name') }}</strong>
                                    </span>
                            </div>
                        </div>

                        <div class="form-group{{ $errors->has('email') ? ' has-error' : '' }}">
                            <label for="email" class="col-md-4 control-label">E-Mail Address</label>

                            <div class="col-md-6">
                                <input id="email" type="email" class="form-control" name="email" value="{{ old('email') }}" required>

                                    <span class="help-block">
                                        <strong>{{ $errors->first('email') }}</strong>
                                    </span>
                            </div>
                        </div>

                        <div class="form-group{{ $errors->has('password') ? ' has-error' : '' }}">
                            <label for="password" class="col-md-4 control-label">Password</label>

                            <div class="col-md-6">
                                <input id="password" type="password" class="form-control" name="password" required>

                                    <span class="help-block">
                                        <strong>{{ $errors->first('password') }}</strong>
                                    </span>
                            </div>
                        </div>

                        <div class="form-group{{ $errors->has('password_confirmation') ? ' has-error' : '' }}">
                            <label for="password-confirm" class="col-md-4 control-label">Confirm Password</label>

                            <div class="col-md-6">
                                <input id="password-confirm" type="password" class="form-control" name="password_confirmation" required>

                                    <span class="help-block">
                                        <strong>{{ $errors->first('password_confirmation') }}</strong>
                                    </span>
                            </div>
                        </div>

                        <div class="form-group">
                            <div class="col-md-6 col-md-offset-4">
                                <button type="submit" class="btn btn-primary">
                                    Register
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

Layouts/app.blade.php

Edit the base layout template that stored on resources/views/layouts/app.blade.php. Near the top of the file add a meta tag to make the csrf-token available for the JavaScript ajax function and At the bottom of the app.blade base layout file, before the closing body tag, add the JavaScript.

This full source code of app.blade.php

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- CSRF Token -->
    <meta name="csrf-token" content="{{ csrf_token() }}">

    <title>{{ config('app.name', 'Laravel') }}</title>

    <!-- Styles -->
    <link href="/css/app.css" rel="stylesheet">

    <!-- Scripts -->
    <script>
        window.Laravel = <?php echo json_encode([
            'csrfToken' => csrf_token(),
        ]); ?>
    </script>
</head>
<body>
    <div id="app">
        <nav class="navbar navbar-default navbar-static-top">
            <div class="container">
                <div class="navbar-header">

                    <!-- Collapsed Hamburger -->
                    <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#app-navbar-collapse">
                        <span class="sr-only">Toggle Navigation</span>
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                    </button>

                    <!-- Branding Image -->
                    <a class="navbar-brand" href="{{ url('/') }}">
                        {{ config('app.name', 'Laravel') }}
                    </a>
                </div>

                <div class="collapse navbar-collapse" id="app-navbar-collapse">
                    <!-- Left Side Of Navbar -->
                    <ul class="nav navbar-nav">
                        &nbsp;
                    </ul>

                    <!-- Right Side Of Navbar -->
                    <ul class="nav navbar-nav navbar-right">
                        <!-- Authentication Links -->
                        @if (Auth::guest())
                            <li><a href="{{ url('/login') }}">Login</a></li>
                            <li><a href="{{ url('/register') }}">Register</a></li>
                        @else
                            <li class="dropdown">
                                <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">
                                    {{ Auth::user()->name }} <span class="caret"></span>
                                </a>

                                <ul class="dropdown-menu" role="menu">
                                    <li>
                                        <a href="{{ url('/logout') }}"
                                            onclick="event.preventDefault();
                                                     document.getElementById('logout-form').submit();">
                                            Logout
                                        </a>

                                        <form id="logout-form" action="{{ url('/logout') }}" method="POST" style="display: none;">
                                            {{ csrf_field() }}
                                        </form>
                                    </li>
                                </ul>
                            </li>
                        @endif
                    </ul>
                </div>
            </div>
        </nav>

        @yield('content')
    </div>

    <!-- Scripts -->
    <script src="/js/app.js"></script>

    <script>
    $(function() {

        var app = {
            DOM: {},
            init: function () {

                // only applies to register form
                if (window.location.pathname == '/register') {

                    this.DOM.form = $('form');
                    this.DOM.form.name  = this.DOM.form.find('input[name="name"]');
                    this.DOM.form.email = this.DOM.form.find('input[name="email"]');
                    this.DOM.form.pwd   = this.DOM.form.find('input[name="password"]');
                    this.DOM.form.pwdc  = this.DOM.form.find('input[name="password_confirmation"]');

                    this.DOM.form.name.group = this.DOM.form.name.closest('.form-group');
                    this.DOM.form.email.group = this.DOM.form.email.closest('.form-group');
                    this.DOM.form.pwd.group = this.DOM.form.pwd.closest('.form-group');

                    this.DOM.form.submit( function(e) {
                        e.preventDefault();

                        var self = this; // native form object

                        error = {};

                        app.DOM.form.name.group.find('strong').text('');
                        app.DOM.form.email.group.find('strong').text('');
                        app.DOM.form.pwd.group.find('strong').text('');

                        app.DOM.form.name.group.removeClass('has-error');
                        app.DOM.form.email.group.removeClass('has-error');
                        app.DOM.form.pwd.group.removeClass('has-error');

                        var user = {};
                        user.name = app.DOM.form.name.val();
                        user.email = app.DOM.form.email.val();
                        user.password = app.DOM.form.pwd.val();
                        user.password_confirmation = app.DOM.form.pwdc.val();

                        var request = $.ajax({
                            headers: {
                                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                            },
                            url: '/validate/user',
                            type: 'POST',
                            contentType: 'application/json',
                            data: JSON.stringify(user)
                        });
                        request.done( function(data)
                        {
                            // native form submit
                            self.submit();
                        });
                        request.fail( function(jqXHR)
                        {
                            error = jqXHR.responseJSON;
                            if (error.name) {
                                app.DOM.form.name.group.find('strong').text(error.name[0]);
                                app.DOM.form.name.group.addClass('has-error');
                            }
                            if (error.email) {
                                app.DOM.form.email.group.find('strong').text(error.email[0]);
                                app.DOM.form.email.group.addClass('has-error');
                            }
                            if (error.password) {
                                app.DOM.form.pwd.group.find('strong').text(error.password[0]);
                                app.DOM.form.pwd.group.addClass('has-error');
                            }

                        });

                    });
                }
            }
        }
        app.init();
    });
    </script>
</body>
</html>

Video tutorial User Authentication with Ajax Validation in laravel 5.3



Download User Authentication with Ajax Validation in laravel 5.3

See you next lessons....

laravel 5 tutorial : User Authentication with Ajax Validation in laravel 5.3


Laravel 5.3 tutorial - Working with Ajax, we can create User Authentication with Ajax Validation, At the previews tutorial, we have learn how to crate User authentication in laravel 5.3, please read for more detail here.

How to add Ajax form validation to Laravel User Authentication that is generated by the Artisan console.

User Authentication with Ajax Validation

First step, we will create new database named with "authentication_db" or anything you want, and next crate new Laravel project using composer, please read How to Install laravel.

User Authentication with Ajax Validation in laravel 5.3

Create Laravel Project

cd c:\xampp\htdocs
......
composer create-project --prefer-dist laravel/laravel hckr

"hckr" is our project name, you change it with another name.

After finished, open your project with Text Editor (i'm using Atom Tex Editor).

Create Connection

Configuration our project to connect to database, Open your .ENV file and configuration with yours.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=hckr_db
DB_USERNAME=root
DB_PASSWORD=yourpassword

Generate Authentication

Create default authentication from laravel following by this Artisan Comamand.

php artisan make:auth

Now the Laravel site has routes and views to allow a user to register, login, logout, and reset their password. A HomeController has also been added to allow authenticated users to enter its view.

Database Migration

To migrate our "users" table run migration following by this command

php artisan migrate

User Model

Next create a folder named with "Models" in the app directory and then move the User.php model into app/Models/.
or you can run this command

mkdir app/Models
....
mv app/User.php app/Models

Next, we need to update the App namespace to App\Models. And adding the public function rules() to the class.

<?php
namespace App\Models;
use Illuminate\Notifications\Notifiable;
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',
    ];
    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];
    public function rules(){
      return [
        'name' => 'required|max:255',
        'email' => 'required|email|max:255|unique:users',
        'password' => 'required|min:6|confirmed',
      ];
    }
}

Registration Controller

Locate the validator function and replace the array of rules being passed to the Validator make method with a call to the newly created rules method in our User model.

<?php

namespace App\Http\Controllers\Auth;

use App\Models\User;
use Validator;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\Registers\Users;

class RegisterController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Register Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles the registration of new users as well as their
    | validation and creation. By default this controller uses a trait to
    | provide this functionality without requiring any additional code.
    |
    */

    use RegistersUsers;

    /**
     * Where to redirect users after login / 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 IlluminateContractsValidationValidator
     */
    protected function validator(array $data)
    {
        return Validator::make($data, (new User)->rules());
    }

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

Config/Auth.php

Edit, config/auth.php, update the authentication drivers user provider.

'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => AppModelsUser::class,
        ],

        // 'users' => [
        //     'driver' => 'database',
        //     'table' => 'users',
        // ],
    ],

User Validation Controller

Create a new Validation folder in Controllers following by this command.

mkdir app/Http/Controllers/Validation

Create a new controller: app/Http/Controllers/Validation/UserController.php in the new Validation folder. It has a single method that applies the rules from the User model for validation.

<?php
namespace App\Http\Controllers\Validation;
use App\Models\User;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Http\Requests;
class UserController extends Controller
{
   public function user(Request $request){
     $this->validate($request, (new User)->rules());
   }
}

Routes (Routes/web.php)

Create new route into routes/web.php file to register a route group using api middleware. Inside this group add a validate/user route that accepts a POST method. The request is then sent to the new Validation\UserController user method for validation.

<?php

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| This file is where you may define all of the routes that are handled
| by your application. Just tell Laravel the URIs it should respond
| to using a Closure or controller method. Build something great!
|
*/

Route::get('/', function () {
    return view('welcome');
});

Route::group(['middleware' => ['api']], function () {
    Route::post('validate/user',[
      'uses' => 'ValidationUserController@user',
    ]);
});

Auth::routes();

Route::get('/home', 'HomeController@index');

Register Form Template

Edit the user registration form template, That stored on resources/views/auth/register.blade.php. Remove all the blade if statements that surround the span help blocks. Each of these blocks need to be rendered by the server and made available to the javascript to display any errors.

This full source code from register.blade.php

@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row">
        <div class="col-md-8 col-md-offset-2">
            <div class="panel panel-default">
                <div class="panel-heading">Register</div>
                <div class="panel-body">
                    <form class="form-horizontal" role="form" method="POST" action="{{ url('/register') }}">
                        {{ csrf_field() }}

                        <div class="form-group{{ $errors->has('name') ? ' has-error' : '' }}">
                            <label for="name" class="col-md-4 control-label">Name</label>

                            <div class="col-md-6">
                                <input id="name" type="text" class="form-control" name="name" value="{{ old('name') }}" required autofocus>

                                    <span class="help-block">
                                        <strong>{{ $errors->first('name') }}</strong>
                                    </span>
                            </div>
                        </div>

                        <div class="form-group{{ $errors->has('email') ? ' has-error' : '' }}">
                            <label for="email" class="col-md-4 control-label">E-Mail Address</label>

                            <div class="col-md-6">
                                <input id="email" type="email" class="form-control" name="email" value="{{ old('email') }}" required>

                                    <span class="help-block">
                                        <strong>{{ $errors->first('email') }}</strong>
                                    </span>
                            </div>
                        </div>

                        <div class="form-group{{ $errors->has('password') ? ' has-error' : '' }}">
                            <label for="password" class="col-md-4 control-label">Password</label>

                            <div class="col-md-6">
                                <input id="password" type="password" class="form-control" name="password" required>

                                    <span class="help-block">
                                        <strong>{{ $errors->first('password') }}</strong>
                                    </span>
                            </div>
                        </div>

                        <div class="form-group{{ $errors->has('password_confirmation') ? ' has-error' : '' }}">
                            <label for="password-confirm" class="col-md-4 control-label">Confirm Password</label>

                            <div class="col-md-6">
                                <input id="password-confirm" type="password" class="form-control" name="password_confirmation" required>

                                    <span class="help-block">
                                        <strong>{{ $errors->first('password_confirmation') }}</strong>
                                    </span>
                            </div>
                        </div>

                        <div class="form-group">
                            <div class="col-md-6 col-md-offset-4">
                                <button type="submit" class="btn btn-primary">
                                    Register
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

Layouts/app.blade.php

Edit the base layout template that stored on resources/views/layouts/app.blade.php. Near the top of the file add a meta tag to make the csrf-token available for the JavaScript ajax function and At the bottom of the app.blade base layout file, before the closing body tag, add the JavaScript.

This full source code of app.blade.php

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- CSRF Token -->
    <meta name="csrf-token" content="{{ csrf_token() }}">

    <title>{{ config('app.name', 'Laravel') }}</title>

    <!-- Styles -->
    <link href="/css/app.css" rel="stylesheet">

    <!-- Scripts -->
    <script>
        window.Laravel = <?php echo json_encode([
            'csrfToken' => csrf_token(),
        ]); ?>
    </script>
</head>
<body>
    <div id="app">
        <nav class="navbar navbar-default navbar-static-top">
            <div class="container">
                <div class="navbar-header">

                    <!-- Collapsed Hamburger -->
                    <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#app-navbar-collapse">
                        <span class="sr-only">Toggle Navigation</span>
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                    </button>

                    <!-- Branding Image -->
                    <a class="navbar-brand" href="{{ url('/') }}">
                        {{ config('app.name', 'Laravel') }}
                    </a>
                </div>

                <div class="collapse navbar-collapse" id="app-navbar-collapse">
                    <!-- Left Side Of Navbar -->
                    <ul class="nav navbar-nav">
                        &nbsp;
                    </ul>

                    <!-- Right Side Of Navbar -->
                    <ul class="nav navbar-nav navbar-right">
                        <!-- Authentication Links -->
                        @if (Auth::guest())
                            <li><a href="{{ url('/login') }}">Login</a></li>
                            <li><a href="{{ url('/register') }}">Register</a></li>
                        @else
                            <li class="dropdown">
                                <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">
                                    {{ Auth::user()->name }} <span class="caret"></span>
                                </a>

                                <ul class="dropdown-menu" role="menu">
                                    <li>
                                        <a href="{{ url('/logout') }}"
                                            onclick="event.preventDefault();
                                                     document.getElementById('logout-form').submit();">
                                            Logout
                                        </a>

                                        <form id="logout-form" action="{{ url('/logout') }}" method="POST" style="display: none;">
                                            {{ csrf_field() }}
                                        </form>
                                    </li>
                                </ul>
                            </li>
                        @endif
                    </ul>
                </div>
            </div>
        </nav>

        @yield('content')
    </div>

    <!-- Scripts -->
    <script src="/js/app.js"></script>

    <script>
    $(function() {

        var app = {
            DOM: {},
            init: function () {

                // only applies to register form
                if (window.location.pathname == '/register') {

                    this.DOM.form = $('form');
                    this.DOM.form.name  = this.DOM.form.find('input[name="name"]');
                    this.DOM.form.email = this.DOM.form.find('input[name="email"]');
                    this.DOM.form.pwd   = this.DOM.form.find('input[name="password"]');
                    this.DOM.form.pwdc  = this.DOM.form.find('input[name="password_confirmation"]');

                    this.DOM.form.name.group = this.DOM.form.name.closest('.form-group');
                    this.DOM.form.email.group = this.DOM.form.email.closest('.form-group');
                    this.DOM.form.pwd.group = this.DOM.form.pwd.closest('.form-group');

                    this.DOM.form.submit( function(e) {
                        e.preventDefault();

                        var self = this; // native form object

                        error = {};

                        app.DOM.form.name.group.find('strong').text('');
                        app.DOM.form.email.group.find('strong').text('');
                        app.DOM.form.pwd.group.find('strong').text('');

                        app.DOM.form.name.group.removeClass('has-error');
                        app.DOM.form.email.group.removeClass('has-error');
                        app.DOM.form.pwd.group.removeClass('has-error');

                        var user = {};
                        user.name = app.DOM.form.name.val();
                        user.email = app.DOM.form.email.val();
                        user.password = app.DOM.form.pwd.val();
                        user.password_confirmation = app.DOM.form.pwdc.val();

                        var request = $.ajax({
                            headers: {
                                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                            },
                            url: '/validate/user',
                            type: 'POST',
                            contentType: 'application/json',
                            data: JSON.stringify(user)
                        });
                        request.done( function(data)
                        {
                            // native form submit
                            self.submit();
                        });
                        request.fail( function(jqXHR)
                        {
                            error = jqXHR.responseJSON;
                            if (error.name) {
                                app.DOM.form.name.group.find('strong').text(error.name[0]);
                                app.DOM.form.name.group.addClass('has-error');
                            }
                            if (error.email) {
                                app.DOM.form.email.group.find('strong').text(error.email[0]);
                                app.DOM.form.email.group.addClass('has-error');
                            }
                            if (error.password) {
                                app.DOM.form.pwd.group.find('strong').text(error.password[0]);
                                app.DOM.form.pwd.group.addClass('has-error');
                            }

                        });

                    });
                }
            }
        }
        app.init();
    });
    </script>
</body>
</html>

Video tutorial User Authentication with Ajax Validation in laravel 5.3



Download User Authentication with Ajax Validation in laravel 5.3

See you next lessons....

Thứ Ba, 11 tháng 10, 2016

Laravel 5 Tutorial : Create Multi Databases Connection in laravel 5.3


Laravel 5 Tutorial : Working with database in Laravel 5.3, How to create multi connection into MySQL databases in laravel 5.3. Laravel 5.3 Php framework can handle an application with multi databases access.

At the previews lessons, we have learn how to working with database in laravel, please read How to create connection into database

Multi Connection

In laravel 5.3 database configuration for our laravel project is located at config/database.php. This file contain database connections. You may define all of your database connections in this file. You may specify which connection should be used by default in return array like.

'default' => env('DB_CONNECTION', 'mysql'),

This file included examples for all of the supported database systems. Now let's start how to connect multiple databases in laravel 5.3.

Create Multi Databases Connection in laravel 5.3

First step - Open your laravel project and at the config/database.php add  and declare new multiple databases under connections array, see this default from laravel installations.

'mysql' => [
            'driver' => 'mysql',
            'host' => env('DB_HOST', 'localhost'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE', 'forge'),
            'username' => env('DB_USERNAME', 'forge'),
            'password' => env('DB_PASSWORD', ''),
            'charset' => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix' => '',
            'strict' => true,
            'engine' => null,
        ],

now, to make multi connection edit database.php above and add new connection function. For examples :

'mysql' => [
            'driver' => 'mysql',
            'host' => env('DB_HOST', 'localhost'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE', 'yourdb1'),
            'username' => env('DB_USERNAME', 'yourID'),
            'password' => env('DB_PASSWORD', 'yourpass'),
            'charset' => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix' => '',
            'strict' => true,
            'engine' => null,
        ],
        'mysql2' => [
            'driver' => 'mysql',
            'host' => env('DB_HOST', 'localhost'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE', 'yourdb2'),
            'username' => env('DB_USERNAME', 'yourID'),
            'password' => env('DB_PASSWORD', 'yourpass'),
            'charset' => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix' => '',
            'strict' => true,
            'engine' => null,
        ],

Now we have added to databases in this file with named "yourdb1" and "yourdb2". So initially we have defined our databases. Now we need to play with our multiple databases.

Configure .ENV file

Go to "root/.env" file and remove initial database configuration (remove code looks like below) For more about Environment Configuration. Save .env file and run you queries.

DB_HOST=localhost
DB_DATABASE=''
DB_USERNAME=''
DB_PASSWORD=''

Note : remove all line connection configurations.

Accessing connection and running query with Query Builder :

Next, we can access each connection via the connection() method on the DB facade. The name passed to the connection method should correspond to one of the connections listed in your config/database.php configuration file. To run query you need to make first DB object then you can access data with this object easily like this :

// this will Running query with default connection.
$userArray = DB::table('biodata')->get();
print_r($userArray);

// This will Makeing an object of second DB.             
$users2 = DB::connection('mysql2');
// Getting data with second DB object.
$u = $users2->table('book')->get();
print_r($u);

There are more methods to Connect multiple databases in laravel and access connections.

The default and easy i have shared to connect multiple databases in laravel and access connections and run your queries.


List Video Tutorial laravel 5.3



See you next lessons ...

Laravel 5 Tutorial : Create Multi Databases Connection in laravel 5.3


Laravel 5 Tutorial : Working with database in Laravel 5.3, How to create multi connection into MySQL databases in laravel 5.3. Laravel 5.3 Php framework can handle an application with multi databases access.

At the previews lessons, we have learn how to working with database in laravel, please read How to create connection into database

Multi Connection

In laravel 5.3 database configuration for our laravel project is located at config/database.php. This file contain database connections. You may define all of your database connections in this file. You may specify which connection should be used by default in return array like.

'default' => env('DB_CONNECTION', 'mysql'),

This file included examples for all of the supported database systems. Now let's start how to connect multiple databases in laravel 5.3.

Create Multi Databases Connection in laravel 5.3

First step - Open your laravel project and at the config/database.php add  and declare new multiple databases under connections array, see this default from laravel installations.

'mysql' => [
            'driver' => 'mysql',
            'host' => env('DB_HOST', 'localhost'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE', 'forge'),
            'username' => env('DB_USERNAME', 'forge'),
            'password' => env('DB_PASSWORD', ''),
            'charset' => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix' => '',
            'strict' => true,
            'engine' => null,
        ],

now, to make multi connection edit database.php above and add new connection function. For examples :

'mysql' => [
            'driver' => 'mysql',
            'host' => env('DB_HOST', 'localhost'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE', 'yourdb1'),
            'username' => env('DB_USERNAME', 'yourID'),
            'password' => env('DB_PASSWORD', 'yourpass'),
            'charset' => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix' => '',
            'strict' => true,
            'engine' => null,
        ],
        'mysql2' => [
            'driver' => 'mysql',
            'host' => env('DB_HOST', 'localhost'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE', 'yourdb2'),
            'username' => env('DB_USERNAME', 'yourID'),
            'password' => env('DB_PASSWORD', 'yourpass'),
            'charset' => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix' => '',
            'strict' => true,
            'engine' => null,
        ],

Now we have added to databases in this file with named "yourdb1" and "yourdb2". So initially we have defined our databases. Now we need to play with our multiple databases.

Configure .ENV file

Go to "root/.env" file and remove initial database configuration (remove code looks like below) For more about Environment Configuration. Save .env file and run you queries.

DB_HOST=localhost
DB_DATABASE=''
DB_USERNAME=''
DB_PASSWORD=''

Note : remove all line connection configurations.

Accessing connection and running query with Query Builder :

Next, we can access each connection via the connection() method on the DB facade. The name passed to the connection method should correspond to one of the connections listed in your config/database.php configuration file. To run query you need to make first DB object then you can access data with this object easily like this :

// this will Running query with default connection.
$userArray = DB::table('biodata')->get();
print_r($userArray);

// This will Makeing an object of second DB.             
$users2 = DB::connection('mysql2');
// Getting data with second DB object.
$u = $users2->table('book')->get();
print_r($u);

There are more methods to Connect multiple databases in laravel and access connections.

The default and easy i have shared to connect multiple databases in laravel and access connections and run your queries.


List Video Tutorial laravel 5.3



See you next lessons ...

Laravel 5 Tutorial : Create Maintenance Page in Laravel 5.3


Laravel 5.3 Tutorial - Working with Maintenance page using 503.blade.php in laravel 5.3, If we have an project using laravel, Some time we need to turn on and turn off maintenance page.

Php artisan Command in laravel 5.3 can handle this method, using turn on and turn off command, Please see all Laravel Command.

How to Turn on Maintenance page in Laravel?

Just grab you application path where laravel application installed and simply run below command.

php artisan down

After run that command, try to open your project using browser.

http://localhost:8080

By default installation laravel 5.3,  responses maintenance page stored on 503.blade.php in resources\views\errors\503.blade.php directory.

Create Maintenance Page in Laravel 5.3

<!DOCTYPE html>
<html>
    <head>
        <title>Be right back.</title>
        <link href="https://fonts.googleapis.com/css?family=Lato:100" rel="stylesheet" type="text/css">
        <style>
            html, body {
                height: 100%;
            }

            body {
                margin: 0;
                padding: 0;
                width: 100%;
                color: #B0BEC5;
                display: table;
                font-weight: 100;
                font-family: 'Lato', sans-serif;
            }

            .container {
                text-align: center;
                display: table-cell;
                vertical-align: middle;
            }

            .content {
                text-align: center;
                display: inline-block;
            }

            .title {
                font-size: 72px;
                margin-bottom: 40px;
            }
        </style>
    </head>
    <body>
        <div class="container">
            <div class="content">
                <div class="title">MAINTENANCE MODE.</div>
            </div>
        </div>
    </body>
</html>

How to Turn Off Maintenance Page

Just grab you application path where laravel application installed and simply run below command.

php artisan up

Maintenance Mode

In maintenance mode, a custom view will be displayed for all requests into your application. It’s a check is included in the default middleware stack for your application. If the application is in maintenance mode, an HttpException will be thrown with a status code of 503.

Video Tutorial Create Maintenance Page



See you next lessons ..

Laravel 5 Tutorial : Create Maintenance Page in Laravel 5.3


Laravel 5.3 Tutorial - Working with Maintenance page using 503.blade.php in laravel 5.3, If we have an project using laravel, Some time we need to turn on and turn off maintenance page.

Php artisan Command in laravel 5.3 can handle this method, using turn on and turn off command, Please see all Laravel Command.

How to Turn on Maintenance page in Laravel?

Just grab you application path where laravel application installed and simply run below command.

php artisan down

After run that command, try to open your project using browser.

http://localhost:8080

By default installation laravel 5.3,  responses maintenance page stored on 503.blade.php in resources\views\errors\503.blade.php directory.

Create Maintenance Page in Laravel 5.3

<!DOCTYPE html>
<html>
    <head>
        <title>Be right back.</title>
        <link href="https://fonts.googleapis.com/css?family=Lato:100" rel="stylesheet" type="text/css">
        <style>
            html, body {
                height: 100%;
            }

            body {
                margin: 0;
                padding: 0;
                width: 100%;
                color: #B0BEC5;
                display: table;
                font-weight: 100;
                font-family: 'Lato', sans-serif;
            }

            .container {
                text-align: center;
                display: table-cell;
                vertical-align: middle;
            }

            .content {
                text-align: center;
                display: inline-block;
            }

            .title {
                font-size: 72px;
                margin-bottom: 40px;
            }
        </style>
    </head>
    <body>
        <div class="container">
            <div class="content">
                <div class="title">MAINTENANCE MODE.</div>
            </div>
        </div>
    </body>
</html>

How to Turn Off Maintenance Page

Just grab you application path where laravel application installed and simply run below command.

php artisan up

Maintenance Mode

In maintenance mode, a custom view will be displayed for all requests into your application. It’s a check is included in the default middleware stack for your application. If the application is in maintenance mode, an HttpException will be thrown with a status code of 503.

Video Tutorial Create Maintenance Page



See you next lessons ..

Laravel 5 Crud Tutorial using Ajax & Bootstrap Template in Laravel 5.3


Laravel 5 tutorial - Laravel 5 simple CRUD application will allow you to add new data into database, edit data, displaying all data from database, and delete data by "ID" field.

at the previews lessons, we have learn how to create simple blog in laravel using Bootstrap templates, please read :
  1. How to create Blog in Laravel 5.3
  2. How to create Bootstrap template in Laravel 5.3

Laravel 5 Simple CRUD Operations

First step - we need an database to save all data from our project, so you must create new database before create laravel project, i was created an database (MySQL database) "ajax_crud".

Next, we will create new laravel project in our localhost, to install laravel 5.3 using composer just following this command :

Laravel 5 Crud Tutorial using Ajax & Bootstrap Template in Laravel 5.3

#Create New Project (Ajax Crud)

cd c:\server\htdocs\
....
composer create-project --prefer-dist laravel/laravel AjaxCrud

After finished, open it with your Text Editor like "Atom" text editor.

#Connecting to Database

Open your laravel project "ajaxcrud" using text editor, and create connection configuration in ".ENV" file like this :

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=ajax_crud
DB_USERNAME=root
DB_PASSWORD=yourpassword

Don't forget to save it.

#Create Migration

create migration using Artisan Command by following this command

php artisan make:migration create_post_table

Your migration file will stored on \database\migrations\2016_10_10_160019_create_post_table.php
Add this function into our migration file to create table and columns into database.

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreatePostTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
      Schema::create('blog_post', function (Blueprint $table) {
      $table->increments('id');
      $table->string('title');
      $table->string('description');
      $table->timestamps();
      });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('blog_post');
    }
}

Next, do migration following by this command

php artisan migrate

#Create Model

Create model following by this command :

php artisan make:model Blog

You have create model with name "Blog.php" and stored on app\Blog.php

#Create Route

create new route, the route file is stored on routes\web.php

Route::group(['middleware' => ['web']], function() {
  Route::resource('blog','BlogController');  
});

blog : is an directory (blog directory) that we create for our views.

#Create Views

Next we will create views using bootstrap templates. to integrate bootstrap in laravel go to this link.
i assume you have download and install bootstrap theme in our project.

Next we create new folder ('blog") under resources\views\blog folder,


we will create three file in blog folder like :
  1. index.blade.php (our home crud project)
  2. create.blade.php (pages to create new data)
  3. edit.blade.php (new pages to edit data)
Because we using System templates, we must create "Master Template" under resources\views\master.blade.php

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Ajax CRUD with Laravel 5.3</title>

    <!-- Bootstrap -->
    <link rel="stylesheet" href="{{ asset('/css/bootstrap.min.css') }}">
    <link rel="stylesheet" href="{{ asset('/css/font-awesome.min.css') }}">

    <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.2/html5shiv.js"></script>
      <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
    <![endif]-->
  </head>
  <body>
    <nav class="navbar navbar-default" role="navigation">
      <div class="container-fluid">
        <div class="navbar-header">
          <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar">
            <span class="sr-only">Toggle navigation</span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
          </button>
          <a class="navbar-brand" href="#">AjaxCrud</a>
        </div>

        <!-- Collect the nav links, forms, and other content for toggling -->
        <div class="collapse navbar-collapse" id="navbar">
          <ul class="nav navbar-nav">
            <li class="active"><a href="/blog">Home</a></li>
            <li><a href="#"></a></li>

          </ul>
          <form class="navbar-form navbar-left" role="search">
            <div class="form-group">
              <input type="text" class="form-control" placeholder="Search">
            </div>
            <button type="submit" class="btn btn-default">Submit</button>
          </form>
          <ul class="nav navbar-nav navbar-right">
            <li><a href="#"></a></li>

          </ul>
        </div><!-- /.navbar-collapse -->
      </div><!-- /.container-fluid -->
    </nav>
    <div class="container">
      <div class="row">
        @yield('content')
      </div>
    </div>

    <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    <!-- Include all compiled plugins (below), or include individual files as needed -->
    <script src="{{ asset('/js/bootstrap.min.js') }}"></script>
  </body>
</html>

#Source code index.blade.php

@extends('master')
  @section('content')
  <div class="row">
    <div class="col-md-12">
      <h1>Simple Ajax CRUD</h1>
    </div>
  </div>
  <div class="row">
    <table class="table table-striped">
      <tr>
        <th>No.</th>
        <th>Title</th>
        <th>Description</th>
        <th>Actions</th>
      </tr>
      <a href="{{route('blog.create')}}" class="btn btn-info pull-right">Create New Data</a><br><br>
      <?php $no=1; ?>
      @foreach($blogs as $blog)
        <tr>
          <td>{{$no++}}</td>
          <td>{{$blog->title}}</td>
          <td>{{$blog->description}}</td>
          <td>
            <form class="" action="{{route('blog.destroy',$blog->id)}}" method="post">
              <input type="hidden" name="_method" value="delete">
              <input type="hidden" name="_token" value="{{ csrf_token() }}">
              <a href="{{route('blog.edit',$blog->id)}}" class="btn btn-primary">Edit</a>
              <input type="submit" class="btn btn-danger" onclick="return confirm('Are you sure to delete this data');" name="name" value="delete">
            </form>
          </td>
        </tr>
      @endforeach
    </table>
  </div>
  @stop

#Source code create.blade.php

@extends('master')
  @section('content')
  <div class="row">
    <div class="col-md-12">
      <h1>Create Data</h1>
    </div>
  </div>
  <div class="row">
    <div class="col-md-12">
      <form class="" action="{{route('blog.store')}}" method="post">
        {{csrf_field()}}
        <div class="form-group{{ ($errors->has('title')) ? $errors->first('title') : '' }}">
          <input type="text" name="title" class="form-control" placeholder="Enter Title Here">
          {!! $errors->first('title','<p class="help-block">:message</p>') !!}
        </div>
        <div class="form-group{{ ($errors->has('description')) ? $errors->first('title') : '' }}">
          <input type="text" name="description" class="form-control" placeholder="Enter Description Here">
          {!! $errors->first('description','<p class="help-block">:message</p>') !!}
        </div>
        <div class="form-group">
          <input type="submit" class="btn btn-primary" value="save">
        </div>
      </form>
    </div>
  </div>
  @stop

#Source code edit.blade.php

@extends('master')
  @section('content')
  <div class="row">
    <div class="col-md-12">
      <h1>Edit Data</h1>
    </div>
  </div>
  <div class="row">
    <form class="" action="{{route('blog.update',$blog->id)}}" method="post">
      <input name="_method" type="hidden" value="PATCH">
      {{csrf_field()}}
      <div class="form-group{{ ($errors->has('title')) ? $errors->first('title') : '' }}">
        <input type="text" name="title" class="form-control" placeholder="Enter Title Here" value="{{$blog->title}}">
        {!! $errors->first('title','<p class="help-block">:message</p>') !!}
      </div>
      <div class="form-group{{ ($errors->has('description')) ? $errors->first('title') : '' }}">
        <input type="text" name="description" class="form-control" placeholder="Enter Description Here" value="{{$blog->description}}">
        {!! $errors->first('description','<p class="help-block">:message</p>') !!}
      </div>
      <div class="form-group">
        <input type="submit" class="btn btn-primary" value="save">
      </div>
    </form>
  </div>
  @stop

#Create BlogController

After all views have create, finally we need to create new controller (BlogController.php), create new controller following this artisan command:

php artisan make:controller BlogController --resource

Your new controller will stored on app\Http\Controllers\BlogController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;

use App\Blog;

class BlogController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return IlluminateHttpResponse
     */
    public function index()
    {
        //show data
        $blogs =  Blog::all();
        return view('blog.index',['blogs' => $blogs]);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return IlluminateHttpResponse
     */
    public function create()
    {
        //create new data
        return view('blog.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  IlluminateHttpRequest  $request
     * @return IlluminateHttpResponse
     */
    public function store(Request $request)
    {
       // validation
      $this->validate($request,[
      'title'=> 'required',
      'description' => 'required',
    ]);
      // create new data
    $blog = new blog;
    $blog->title = $request->title;
    $blog->description = $request->description;
    $blog->save();
    return redirect()->route('blog.index')->with('alert-success','Data Hasbeen Saved!');

    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return IlluminateHttpResponse
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return IlluminateHttpResponse
     */
    public function edit($id)
    {
        $blog = Blog::findOrFail($id);
        // return to the edit views
        return view('blog.edit',compact('blog'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  IlluminateHttpRequest  $request
     * @param  int  $id
     * @return IlluminateHttpResponse
     */
    public function update(Request $request, $id)
    {
        // validation
        $this->validate($request,[
          'title'=> 'required',
          'description' => 'required',
      ]);

        $blog = Blog::findOrFail($id);
        $blog->title = $request->title;
        $blog->description = $request->description;
        $blog->save();

        return redirect()->route('blog.index')->with('alert-success','Data Hasbeen Saved!');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return IlluminateHttpResponse
     */
    public function destroy($id)
    {
        // delete data
        $blog = Blog::findOrFail($id);
        $blog->delete();
        return redirect()->route('blog.index')->with('alert-success','Data Hasbeen Saved!');
    }
}

Video Tutorial Laravel 5.3 Crud Operations


Laravel 5.3 CRUD with VueJS



Download full source code.
see you next lessons.