Restaurant Management System ( Part 3 )

Published Date: 03-Jan-2018 | Tags: Laravel 5.5  Bootstrap 3  Project  

In this tutorial, I will show you how user redirect to their page base on their role, and how to manage login users. And the last section is that how user can change thier own password.

Note: I recommend you to check all pervious tutorials before coming to this step. Because some tutorials have relationship with others. 

  

Step 1: Update Login Code

Edit this file /app/Http/Controllers/Auth/LoginController.php, change property $redirectTo to "/", and override username() and credentials() function. 

In our case, user can login unless they provide a correct username and password. And it is an active account.

<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;

class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

    use AuthenticatesUsers;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = '/';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest', ['except' => 'logout']);
    }

    public function username()
    {
        return 'username';
    }

    protected function credentials(Request $request)
    {
        return $request->only($this->username(), 'password', 'active');
    }
}

 

Step 2: Create Views (User Management Section)

Create this view index.blade.php in /resources/views/user. (create folder user if it does not exist)

<h2 class="page-header">User Management
    <div class="pull-right">
        <a href="javascript:ajaxLoad('user/create')" class="btn btn-primary pull-right"><i
                    class="glyphicon glyphicon-plus-sign"></i> New</a>
    </div>
</h2>
<div class="col-md-3 form-group">
    {!! Form::select('role',['-1'=>'All Roles','Admin'=>'Admin','Cashier'=>'Cashier'],Session::get('user_role'),['class'=>'form-control','style'=>'height:auto','onChange'=>'ajaxLoad("'.url("user").'?role="+this.value)']) !!}
</div>
<div class="col-md-4 form-group">
    <div class="input-group">
        <input class="form-control" id="search" value="{{ Session::get('user_search') }}"
               onkeydown="if (event.keyCode == 13) ajaxLoad('{{url('user')}}?ok=1&search='+this.value)"
               placeholder="Search..."
               type="text">

        <div class="input-group-btn">
            <button type="button" class="btn btn-default"
                    onclick="ajaxLoad('{{url('user')}}?ok=1&search='+$('#search').val())"><i
                        class="glyphicon glyphicon-search"></i>
            </button>
        </div>
    </div>
</div>
<table class="table table-bordered table-striped">
    <thead>
    <tr>
        <th width="50px" style="text-align: center">No</th>
        <th class="hidden-xs hidden-sm">
            <a href="javascript:ajaxLoad('user?field=username&sort={{Session::get("user_sort")=="asc"?"desc":"asc"}}')">
                Username
            </a>
            <i style="font-size: 12px"
               class="glyphicon  {{ Session::get('user_field')=='username'?(Session::get('user_sort')=='asc'?'glyphicon-sort-by-alphabet':'glyphicon-sort-by-alphabet-alt'):'' }}">
            </i>
        </th>
        <th class="hidden-xs hidden-sm">Role</th>
        <th width="50" align="center">Active</th>
        <th width="140px"></th>
    </tr>
    </thead>
    <tbody>
    <?php $i = 1;?>
    @foreach($users as $key=>$user)
        <tr>
            <td align="center">{{$i++}}</td>
            <td>{{$user->username}}</td>
            <td class="hidden-xs hidden-sm">{{$user->role}}</td>
            <td align="center">
                {!!$user->active?"<i  style='color:green' class='glyphicon glyphicon-ok'></i>":"<i style='color: red'
                                                                                                 class='glyphicon glyphicon-remove'></i>"!!}
            </td>
            <td style="text-align: center">
                <a class="btn btn-primary btn-xs" title="Edit"
                   href="javascript:ajaxLoad('user/update/{{$user->id}}')">
                    <i class="glyphicon glyphicon-edit"></i> Edit</a>
                <a class="btn btn-danger btn-xs" title="Delete"
                   href="javascript:if(confirm('Are you sure want to delete?')) ajaxDelete('user/delete/{{$user->id}}','{{csrf_token()}}')">
                    <i class="glyphicon glyphicon-trash"></i> Delete
                </a>
            </td>
        </tr>
    @endforeach
    </tbody>
</table>
<div class="pull-right">{!! str_replace('/?','?',$users->render()) !!}</div>
<div class="row">
    <i class="col-sm-12">
        Total: {{$users->total()}} records
    </i>
</div>

 

Create this view form.blade.php in /resources/views/user. (create folder user if it does not exist)

<h2 class="page-header">{{isset($user)?'Edit':'New'}}User</h2>
@if(isset($user))
    {!! Form::model($user,["id"=>"frm","class"=>"form-horizontal","method"=>"put"]) !!}
@else
    {!! Form::open(["id"=>"frm","class"=>"form-horizontal"]) !!}
@endif
<div class="row">
    <div class="form-group required" id="form-username-error">
        {!! Form::label("username","Username",["class"=>"control-label col-md-2"]) !!}
        <div class="col-md-5">
            {!! Form::text("username",null,["class"=>"form-control required","id"=>"focus"]) !!}
            <span id="username-error" class="help-block"></span>
        </div>
    </div>
    <div class="form-group">
        {!! Form::label("role","Role",["class"=>"control-label col-md-2"]) !!}
        <div class="col-md-5">
            {!! Form::select("role",['Admin'=>'Admin','Cashier'=>'Cashier'],null,["class"=>"form-control"]) !!}
        </div>
    </div>
    <div class="form-group" id="form-password-error">
        {!! Form::label("password","Password",["class"=>"control-label col-md-2"]) !!}
        <div class="col-md-5">
            {!! Form::password("password",["class"=>"form-control required"]) !!}
            <span id="password-error" class="help-block"></span>
        </div>
    </div>
    <div class="form-group">
        {!! Form::label("password_confirmation","Confirm password",["class"=>"control-label col-md-2"]) !!}
        <div class="col-md-5">
            {!! Form::password("password_confirmation",["class"=>"form-control"]) !!}
        </div>
    </div>
    <div class="form-group">
        {!! Form::label("active","Active",["class"=>"control-label col-md-2"]) !!}
        <div class="col-md-5">
            {!! Form::checkbox("active",1,null,["style"=>"width:25px;height:25px"]) !!}
        </div>
    </div>
    <div class="form-group">
        <div class="col-md-5 col-md-push-2">
            <a href="javascript:ajaxLoad('{{url('user')}}')"
               class="btn btn-danger"><i
                        class="glyphicon glyphicon-backward"></i> Back</a>
            {!! Form::button("<i class='glyphicon glyphicon-floppy-disk'></i> Save",["type" => "submit","class"=>"btn
        btn-primary","id"=>"btn_save"])!!}
        </div>
    </div>
</div>
{!! Form::close() !!}

 

Create this view change_password.blade.php in /resources/views/user. (create folder user if it does not exist)

@if(Session::pull('change_password'))
    <div class="alert alert-success">
        <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span
                    aria-hidden="true">&times;</span></button>
        <b><i class="glyphicon glyphicon-ok-sign"></i> Congratulation!</b> You have successfully changed your password.
    </div>
@endif
<h3 class="page-header">Change Password</h3>
{!! Form::model($user,["id"=>"createForm","class"=>"form-horizontal","method"=>"put"]) !!}
<div class="form-group required" id="form-old_password-error">
    {!! Form::label("old_password","Old Password",["class"=>"control-label col-md-3"]) !!}
    <div class="col-md-6">
        {!! Form::password("old_password",["class"=>"form-control required","id"=>"focus"]) !!}
        <div id="old_password-error" class="help-block"></div>
    </div>
</div>
<div class="form-group" id="form-password-error">
    {!! Form::label("password","Password",["class"=>"control-label col-md-3"]) !!}
    <div class="col-md-6">
        {!! Form::password("password",["class"=>"form-control required"]) !!}
        <div id="password-error" class="help-block"></div>
    </div>
</div>
<div class="form-group">
    {!! Form::label("password_confirmation","Confirm password",["class"=>"control-label col-md-3"]) !!}
    <div class="col-md-6">
        {!! Form::password("password_confirmation",["class"=>"form-control"]) !!}
    </div>
</div>
<div class="form-group">
    <div class="col-md-6 col-md-push-3">
        {!! Form::button("<i class='glyphicon glyphicon-floppy-disk'></i> Save",["type" => "submit","class"=>"btn
        btn-primary","id"=>"btn_save"])!!}
    </div>
</div>
{!! Form::close() !!}
<script>
    $("#createForm").submit(function (event) {
        $("#btn_save").attr('disabled', 'disabled').html("<i class='glyphicon glyphicon-floppy-disk'></i> Saving...");
        event.preventDefault();
        var form = $(this);
        var data = form.serialize();
        var url = form.attr("action");
        $.ajax({
            type: "POST",
            url: url,
            data: data,
            cache: false,
            success: function (data) {
                if (data.fail) {
                    $('input.required, textarea.required').each(function () {
                        index = $(this).attr('name');
                        if (index in data.errors) {
                            $("#form-" + index + "-error").addClass("has-error");
                            $("#" + index + "-error").html(data.errors[index]);
                        }
                        else {
                            $("#form-" + index + "-error").removeClass("has-error");
                            $("#" + index + "-error").empty();
                        }
                    });
                } else {
                    $(".has-error").removeClass("has-error");
                    $(".help-block").empty();
                    var url = window.location.href;
                    var controllerAction = url.substr(url.indexOf('#') + 1);
                    ajaxLoad(controllerAction);
                }
                $("#focus").focus();
                $("#btn_save").removeAttr('disabled').html("<i class='glyphicon glyphicon-floppy-disk'></i> Save");
            },
            error: function (xhr, textStatus, errorThrown) {
                alert(errorThrown);
            }
        });
        return false;
    });
</script>

 

 

Step 3: Create User Controller

Please create UserController.php in /app/Http/Controllers.

<?php
namespace App\Http\Controllers;

use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Validator;

class UserController extends Controller
{
    public function index()
    {
        Session::put('user_search', Input::has('ok') ? Input::get('search') : (Session::has('user_search') ? Session::get('user_search') : ''));
        Session::put('user_field', Input::has('field') ? Input::get('field') : (Session::has('user_field') ? Session::get('user_field') : 'username'));
        Session::put('user_role', Input::has('role') ? Input::get('role') : (Session::has('user_role') ? Session::get('user_role') : -1));
        Session::put('user_sort', Input::has('sort') ? Input::get('sort') : (Session::has('user_sort') ? Session::get('user_sort') : 'asc'));
        $users = new User();
        if (Session::get('user_role') != -1)
            $users = $users->where('role', Session::get('user_role'));
        $users = $users->where('username', 'like', '%' . Session::get('user_search') . '%')
            ->where('role', '!=', 'SuperAdmin')
            ->orderBy(Session::get('user_field'), Session::get('user_sort'))->paginate(20);
        return view('user.index', ['users' => $users]);
    }

    public function update(Request $request, $id)
    {
        if ($request->isMethod('get'))
            return view('user.form', ['user' => User::find($id)]);
        else {
            $user = User::find($id);
            $rules = [];
            if (strtolower($user->username) != strtolower(Input::get('username')))
                $rules += ['username' => 'required|alpha_dash|unique:users'];
            if (Input::get('password') != '')
                $rules += ['password' => 'confirmed'];
            $validator = Validator::make(Input::all(), $rules);
            if ($validator->fails()) {
                return array(
                    'fail' => true,
                    'errors' => $validator->getMessageBag()->toArray()
                );
            }
            $user->username = Input::get('username');
            $user->role = Input::get('role');
            if (Input::get('password') != '')
                $user->password = bcrypt(Input::get('password'));
            $user->active = Input::get('active') ? 1 : 0;
            $user->save();
            Session::put('msg_status', true);
        }
    }

    public function create(Request $request)
    {
        if ($request->isMethod('get'))
            return view('user.form');
        else {
            $validator = Validator::make(Input::all(), [
                "username" => "required|alpha_dash|unique:users",
                'password' => 'required|confirmed'
            ]);
            if ($validator->fails()) {
                return array(
                    'fail' => true,
                    'errors' => $validator->getMessageBag()->toArray()
                );
            }
            $user = new User();
            $user->username = Input::get('username');
            $user->role = Input::get('role');
            $user->password = bcrypt(Input::get('password'));
            $user->active = Input::get('active') ? 1 : 0;
            $user->save();
            Session::put('msg_status', true);
        }
    }

    public function delete($id)
    {
        User::destroy($id);
        return redirect('user');
    }

    public function changePassword(Request $request)
    {
        if ($request->isMethod('get'))
            return view("user.change_password", ['user' => Auth::user()]);
        else {
            $validator = Validator::make(Input::all(), [
                'old_password' => 'required',
                'password' => 'required|confirmed'
            ]);
            if ($validator->fails()) {
                return array(
                    'fail' => true,
                    'errors' => $validator->getMessageBag()->toArray()
                );
            }
            $user = Auth::user();
            if (Hash::check(Input::get('old_password'), $user->password)) {
                $user->password = Hash::make(Input::get('password'));
                $user->save();
                Session::put('change_password', true);
                return Redirect::back();
            } else
                return array(
                    'fail' => true,
                    'errors' => ["old_password" => "Old Password is incorrect. Please try again!"]
                );
        }
    }
}

 

Step 4: How to Test?

Till this step, what I expect from you is that you can login to the system by using default super user that already stored in the backup database.

Just try to login with username: super and password: super. Then you will see the admin screen as below.

Note: what you can check right now are "User Management" and "Change Password" options on the menu. Beside these 2, you will see the popup error because we not yet implement it. 

user-management

After creating some users, please logout and login as your newly created admin user(cashier user will be error because we not yet implement cashier part), then trying changing its password.

change-password

Hope you can do it. 


Demo


Related Posts

© 2018 All Rights Reserved.