Monday, August 17, 2015

การสร้างฟอร์ม Login / Register php

การสร้างฟอร์ม Login / Register [Ubuntu][php][Laravel4][Sentry]

กระทู้ก่อนหน้า การสร้าง Database สำหรับ Sentry

ทำการแก้ไขไฟล์ HomeController.php ที่อยู่ใน /var/www/laravel/app/controllers/

<?php
class HomeController extends BaseController {
    /*
    |--------------------------------------------------------------------------
    | Default Home Controller
    |--------------------------------------------------------------------------
    |
    | You may wish to use controllers instead of, or in addition to, Closure
    | based routes. That's great! Here is an example controller method to
    | get you started. To route to this controller, just add the route:
    |
    |    Route::get('/', 'HomeController@showWelcome');
    |
    */
    public function showWelcome()
    {
        return View::make('hello');
    }
    public function getRegister()
    {
        return View::make('home.register');
    }
   
    public function getLogin()
    {
        return View::make('home.login');
    }
    public function postRegister()
    {
        try
        {
            $user = Sentry::createUser(array(
                'first_name' => Input::get('first_name'),
                'last_name' => Input::get('last_name'),
                'email' => Input::get('email'),
                'password' => Input::get('password'),
                'activated' => true,
                ));
        }
        catch (Cartalyst\Sentry\Users\UserExistsException $e)
        {
            echo 'User Already Exists';
        }
    }
    public function postLogin()
    {
        $credentials = array(
            'email' => Input::get('email'),
            'password' => Input::get('password'),
            );
        try{
                $user = Sentry::authenticate($credentials, false);
                if($user)
                    {
                        return Redirect::to('admin');
                    }
            }
        catch (\Exception $e)
            {
                return Redirect::to('login')->withErrors(array('login' => $e->getMessages()));
            }
    }
    public function logout()
    {
        Sentry::logout();
        return Redirect::to('/');
    }
   
}



จากนั้นจะทำการสร้างหน้า Login / Register
 โดยทำการ New folder ที่ /var/www/laravel/app/views/
ชื่อ folder ว่า layouts

ทำการสร้างไฟล์ ขึ้นมาชื่อ
default.blade.php

ทำการเพิ่ม Source Code

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    {{ HTML::style('//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css') }}
</head>
<body>
    @yield('content')
    {{ HTML::script('//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js') }}
    {{ HTML::script('//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js') }}
</body>
</html> 


หลังจากนั้นทำการสร้าง file login
โดยสร้าง Folder ใหม่ ไว้ใน /var/www/laravel/app/views/
ชื่อ Folder ว่า home 
และทำการส้รางไฟล์ใหม่ขึ้นมาชื่อว่า  login.blade.php

@extends('layouts.default')

@section('content')

<div class="col-md-4 col-md-offset-4">
      <div class="panel panel-info">
        <div class="panel-heading">Please Login</div>
        <div class="panel-body">
            {{ Form::open(array('url' => 'login')) }}
            @if($errors->has('login'))
                <div class="alert alert-danger">
                    <a href="#" class="close" data-dismiss="alert">&times;</a>
                    {{ $errors->first('login', ':message') }}
                </div>
            @endif
            <div class="form-group">
                {{ Form::label('email', 'Email Address') }}
                {{ Form::text('email', '', array('class' => 'form-control', 'placeholder' => 'Email Address')) }}
            </div>
            <div class="form-group">
                {{ Form::label('password', 'Password') }}
                {{ Form::password('password', array('class' => 'form-control', 'placeholder' => 'Password')) }}
            </div>
            <div class="form-group">
                {{ Form::submit('Login', array('class' => 'btn btn-success')) }}
                {{ HTML::link('/', 'Cancel', array('class' => 'btn btn-danger')) }}
            </div>
            {{ Form::close() }}
        </div>
      </div>
</div>


ทำการเพิ่มการ Register ไว้ในที่เดียวกันโดยใช้ชื่อ  register.blade.php

@extends('layouts.default')

@section('content')

<div class="col-md-4 col-md-offset-4">
      <div class="panel panel-info">
        <div class="panel-heading">Please Register</div>
        <div class="panel-body">
            {{ Form::open(array('url' => 'register')) }}
            @if($errors->any())
                <div class="alert alert-danger">
                    <a href="#" class="close" data-dismiss="alert">&times;</a>
                    {{ implode('', $errors->all('<li class="error">:message</li>')) }}
                </div>
            @endif
            <div class="form-group">
                {{ Form::label('fname', 'First Name') }}
                {{ Form::text('first_name', '', array('class' => 'form-control', 'placeholder' => 'First Name')) }}
            </div>
            <div class="form-group">
                {{ Form::label('last_name', 'Last Name') }}
                {{ Form::text('last_name', '', array('class' => 'form-control', 'placeholder' => 'Last Name')) }}
            </div>
            <div class="form-group">
                {{ Form::label('email', 'Email Address') }}
                {{ Form::text('email', '', array('class' => 'form-control', 'placeholder' => 'Email Address')) }}
            </div>
            <div class="form-group">
                {{ Form::label('password', 'Password') }}
                {{ Form::password('password', array('class' => 'form-control', 'placeholder' => 'Password')) }}
            </div>
            <div class="form-group">
                {{ Form::submit('Register', array('class' => 'btn btn-success')) }}
                {{ HTML::link('/', 'Cancel', array('class' => 'btn btn-danger')) }}
            </div>
            {{ Form::close() }}
        </div>
      </div>
</div>


@stop


หลังจากนั้น ทำการแก้ไขไฟล์ routes.php ซึ่งอยู่ใน  /var/www/laravel/app/

<?php
/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the Closure to execute when that URI is requested.
|
*/
Route::get('/', function()
{
    return View::make('hello');
});
Route::get('register', 'HomeController@getRegister');
Route::get('login', 'HomeController@getLogin');
Route::post('login', 'HomeController@postLogin');
Route::post('register', 'HomeController@postRegister');
Route::group(array('before' => 'auth'), function(){
    Route::get('admin', 'AdminController@index');
    Route::get('logout', 'HomeController@logout');
});



หลังจากนั้น ทำการแก้ไขไฟล์ fifters.php ซึ่งอยู่ใน  /var/www/laravel/app/

<?php
/*
|--------------------------------------------------------------------------
| Application & Route Filters
|--------------------------------------------------------------------------
|
| Below you will find the "before" and "after" events for the application
| which may be used to do any work before or after a request into your
| application. Here you may also register your custom route filters.
|
*/
App::before(function($request)
{
    //
});
App::after(function($request, $response)
{
    //
});
/*
|--------------------------------------------------------------------------
| Authentication Filters
|--------------------------------------------------------------------------
|
| The following filters are used to verify that the user of the current
| session is logged into this application. The "basic" filter easily
| integrates HTTP Basic authentication for quick, simple checking.
|
*/
// Route::filter('auth', function()
// {
//     if (Auth::guest()) return Redirect::guest('login');
// });
Route::filter('auth', function(){
    if(!Sentry::check()) return Redirect::guest('login');
});
Route::filter('auth.basic', function()
{
    return Auth::basic();
});
/*
|--------------------------------------------------------------------------
| Guest Filter
|--------------------------------------------------------------------------
|
| The "guest" filter is the counterpart of the authentication filters as
| it simply checks that the current user is not logged in. A redirect
| response will be issued if they are, which you may freely change.
|
*/
Route::filter('guest', function()
{
    if (Auth::check()) return Redirect::to('/');
});
/*
|--------------------------------------------------------------------------
| CSRF Protection Filter
|--------------------------------------------------------------------------
|
| The CSRF filter is responsible for protecting your application against
| cross-site request forgery attacks. If this special token in a user
| session does not match the one given in this request, we'll bail.
|
*/
Route::filter('csrf', function()
{
    if (Session::token() != Input::get('_token'))
    {
        throw new Illuminate\Session\TokenMismatchException;
    }
}); 



จากนั้นสร้าง Folder ใหม่ ไว้ใน /var/www/laravel/app/views/
ชื่อ Folder ว่า admin
ทำการส้รางไฟล์ใหม่ โดยใช้ชื่อว่า index.blade.php


 @extends('layouts.default')

@section('content')


<h2>Admin Section</h2>

    {{ HTML::link('logout', 'Logout', array('class' => 'btn btn-warning'))}}


@stop



สุดท้ายทำการสร้างไฟล์ชื่อว่า AdminController.php  ไว้ใน /var/www/laravel/

<?php
class AdminController extends BaseController {
    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function index()
    {
        return View::make('admin.index');
    }
    /**
     * Show the form for creating a new resource.
     *
     * @return Response
     */
    public function create()
    {
        return View::make('admins.create');
    }
    /**
     * Store a newly created resource in storage.
     *
     * @return Response
     */
    public function store()
    {
        //
    }
    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return Response
     */
    public function show($id)
    {
        return View::make('admins.show');
    }
    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return Response
     */
    public function edit($id)
    {
        return View::make('admins.edit');
    }
    /**
     * Update the specified resource in storage.
     *
     * @param  int  $id
     * @return Response
     */
    public function update($id)
    {
        //
    }
    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return Response
     */
    public function destroy($id)
    {
        //
    }
}



สามารถใช้งานได้โดยเข้าไปที่

Url login : localhost/login

Url Register : localhost/register


ขอขอบคุณ Source Code จาก คุณ..fallendown


No comments:

Post a Comment