Laravel 8 : User Management Part2

Melanjutkan dari postingan Sebelumnya, pada postingan ini akan langsung membuat project laravel dan ngoding :D

Sebelum memulai project laravel pastikan sudah membuat database dengan table-table yang ada di postingan Sebelumnya

setelah semua table-table dibuat, selanjut membuat view pada database, adapun beberapa view yang harus dibuat sebagai berikut :

1. View v_menuroles

CREATE VIEW v_menuroles as select `c`.`rolename` AS `role`,`b`.`roleid` AS `roleid`,`a`.`name` AS `description`,`b`.`menuid` AS `menuid`,`a`.`route` AS `route`,`a`.`menugroup` AS `menugroup`,`d`.`description` AS `groupname` from (((`menus` `a` join `menuroles` `b` on((`a`.`id` = `b`.`menuid`))) join `roles` `c` on((`b`.`roleid` = `c`.`id`))) join `menugroups` `d` on((`a`.`menugroup` = `d`.`id`)))

2. View v_userroles

CREATE VIEW v_userroles as select `a`.`id` AS `id`,`a`.`name` AS `name`,`a`.`email` AS `email`,`b`.`roleid` AS `roleid`,`c`.`rolename` AS `role` from ((`users` `a` join `userroles` `b` on((`a`.`email` = `b`.`email`))) join `roles` `c` on((`b`.`roleid` = `c`.`id`)))

3. View v_usermenus

CREATE VIEW v_usermenus select `a`.`id` AS `id`,`a`.`name` AS `name`,`a`.`email` AS `email`,`b`.`roleid` AS `roleid`,`c`.`rolename` AS `role`,`c`.`rolename` AS `rolename`,`d`.`menuid` AS `menuid`,`e`.`name` AS `menuname`,`e`.`route` AS `route`,`e`.`menugroup` AS `menugroup`,`f`.`description` AS `groupname`,`f`.`icons` AS `groupicon`,`f`.`_index` AS `_index` from (((((`users` `a` join `userroles` `b` on((`a`.`email` = `b`.`email`))) join `roles` `c` on((`b`.`roleid` = `c`.`id`))) join `menuroles` `d` on((`c`.`id` = `d`.`roleid`))) join `menus` `e` on((`d`.`menuid` = `e`.`id`))) join `menugroups` `f` on((`e`.`menugroup` = `f`.`id`))) order by `f`.`_index`,`a`.`id`,`b`.`roleid`,`f`.`id`,`d`.`menuid`

4. Create v_menus

CREATE VIEW v_menus select `a`.`id` AS `id`,`a`.`name` AS `description`,`a`.`route` AS `route`,`a`.`menugroup` AS `menugroup`,`b`.`description` AS `groupname`,`b`.`_index` AS `_index` from (`laravel_user_management`.`menus` `a` join `laravel_user_management`.`menugroups` `b` on((`a`.`menugroup` = `b`.`id`)))


Ok selanjutnya membuat project laravel baru melalui composer dengan menjalankan command berikut :

composer create-project laravel/laravel UserManagement

tunggu proses pembuatan project laravel sampai selesai, jika sudah buka project nya dengan code editor, disini saya menggunakan visual studio code 


 

Selanjutnya siapkan template yang akan digunakan, disini saya menggunakan lumino admin template yang bisa di download DISINI, lalu extract filenya kemudian copy folder css sampai table kedalam folder public yang ada di project laravelnya sehingga tampilan folder public-nya menjadi seperti berikut :



selanjutnya menyiapkan beberapa controller, berikut beberapa controller yang harus dibuat :

php artisan make:controller HomeController
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Carbon\Carbon;
use DB;
use Validator,Redirect,Response;

class HomeController extends Controller
{
    public function index(){
        if(Auth::check()){
            return redirect()->intended('dashboard');
        }
        return view('login');
    }

    public function dashboard(){
        return view('home.dashboard');
    }

    public function login(Request $request){
        $request->validate([
            'email'    => 'required|email:dns',
            'password' => 'required|string'
        ]);

        $options = [
            'cost' => 12,
        ];
        $password = password_hash($request['password'], PASSWORD_BCRYPT, $options);

        $credentials = $request->only('email''password');

        $dataAttempt = array(
            'email'    => strtolower($request['email']),
            'password' => $request['password']
        );

        if (Auth::attempt($credentials)) {
            if(Auth::user()->deletion_flag === "X"){
                Auth::logout();
                return Redirect::back()
                ->withErrors(
                    [
                        'error' => 'Opps! Your account is deleted, please contact System Administrator',
                    ]
                );
            }elseif(Auth::user()->request_change_acc === "Y"){
                Auth::logout();
                return Redirect::back()
                ->withErrors(
                    [
                        'error' => 'Your account temporarily is inactive, your data changes are being verified',
                    ]
                );
            }else{
                return redirect()->intended('dashboard');
            }
        }else{
            return Redirect::back()
                ->withErrors(
                    [
                        'error' => 'Opps! You have entered invalid credentials',
                    ]
                );
        }
    }

    public function logout(Request $request){
        Auth::logout();

        $request->session()->invalidate();

        $request->session()->regenerateToken();

        return redirect('/');
    }

    public function home(){
        if(Auth::check()){
            $nama = $nama = Auth::user()->name;
            return view('home.index',['nama' => $nama]);
        }
        return Redirect::to("login")->withErrors('Opps! You do not have access');
    }
}
php artisan make:controller LoginController
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

use DB;

class LoginController extends Controller
{
    public function authenticate(Request $request)
    {
        $credentials = $request->validate([
            'email' => ['required''email'],
            'password' => ['required'],
        ]);

        if (Auth::attempt($credentials)) {
            $request->session()->regenerate();

            return redirect()->intended('dashboard');
        }

        return back()->withErrors([
            'email' => 'The provided credentials do not match our records.',
        ]);
    }
}
php artisan make:controller Setting\UserController
<?php

namespace App\Http\Controllers\Setting;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;

use Validator,Redirect,Response;
use DB;

class UserController extends Controller
{
    public function index(){
        $data = DB::table('users')->get();
        return view('settings.users.index', ['data' => $data]);
    }

    public function create(){
        return view('settings.users.create');
    }

    public function edit(){
        return view('settings.users.edit');
    }

    public function list(){
        $data['data'] = DB::table('users')
                        ->get();
        return json_encode($data);
    }

    public function save(Request $request){
        $validated = $request->validate([
            'email'    => 'required|unique:users|max:255',
            'name'     => 'required',
            'password' => 'required',
        ]);

        $options = [
            'cost' => 12,
        ];
        $password = password_hash($request['password'], PASSWORD_BCRYPT, $options);

        $output = array();

        DB::beginTransaction();
        try{
            DB::table('users')->insert([
                'name'        => $request['name'],
                'email'       => $request['email'],
                'password'    => $password
            ]);

            DB::commit();
            return Redirect::to("/setting/users")->withSuccess('New User Created');
        }catch(\Exception $e){
            DB::rollBack();
            return Redirect::to("/setting/users")->withError($e->getMessage());
        }
    }
}
php artisan make:controller Setting\RoleController
<?php

namespace App\Http\Controllers\Setting;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;

use Validator,Redirect,Response;
use DB;

class RoleController extends Controller
{
    public function index(){
        $data = DB::table('roles')->get();
        return view('settings.roles.index', ['data' => $data]);
    }

    public function create(){
        $data = DB::table('roles')->get();
        return view('settings.roles.create');
    }

    public function list(){
        if(Auth::check()){
            $data['data'] = DB::table('roles')
                    ->get();
            return json_encode($data);
        }
    }

    public function save(Request $request){
        $validated = $request->validate([
            'rolename' => 'required|unique:roles|max:255'
        ]);

        DB::beginTransaction();
        try{
            DB::table('roles')->insert([
                'rolename' => $request['rolename']
            ]);

            DB::commit();
            return Redirect::to("/setting/roles")->withSuccess('New Role Created');
        }catch(\Exception $e){
            DB::rollBack();
            return Redirect::to("/setting/roles")->withError($e->getMessage());
        }
    }
}
php artisan make:controller Setting\MenuGroupController
<?php

namespace App\Http\Controllers\Setting;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

use Validator,Redirect,Response;
use DB;

class MenuGroupController extends Controller
{
    public function index(){
        $data = DB::table('menugroups')->get();
        return view('settings.menugroups.index', ['data' => $data]);
    }

    public function create(){
        return view('settings.menugroups.create');
    }

    public function save(Request $request){
        DB::beginTransaction();
        try{
            DB::table('menugroups')->insert([
                'description'  => $request['groupname']
            ]);

            DB::commit();
            return Redirect::to("/setting/menugroups")->withSuccess('New Menu Group Created');
        }catch(\Exception $e){
            DB::rollBack();
            return Redirect::to("/setting/menugroups")->withError($e->getMessage());
        }
    }
}
php artisan make:controller Setting\MenuController
<?php

namespace App\Http\Controllers\Setting;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Validator,Redirect,Response;
use DB;

class MenuController extends Controller
{
    public function index(){
        $data = DB::table('menus')->get();
        return view('settings.menus.index', ['data' => $data]);
    }

    public function create(){
        $data = DB::table('menugroups')->get();
        return view('settings.menus.create', ['groups' => $data]);
    }

    public function list(){
        $data['data'] = DB::table('v_menus')
                        ->get();
        return json_encode($data);
    }

    public function save(Request $request){
        DB::beginTransaction();
        try{
            DB::table('menus')->insert([
                'name'      => $request['menuname'],
                'route'     => $request['menuroute'],
                'menugroup' => $request['menugroups']
            ]);

            DB::commit();
            return Redirect::to("/setting/menus")->withSuccess('New Menu Created');
        }catch(\Exception $e){
            DB::rollBack();
            return Redirect::to("/setting/menus")->withError($e->getMessage());
        }
    }
}
php artisan make:controller Setting\MenuRoleController
<?php

namespace App\Http\Controllers\Setting;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

use Validator,Redirect,Response;
use DB;

class MenuRoleController extends Controller
{
    public function index(){
        $data = DB::table('v_menuroles')
        ->orderBy('role',      'asc')
        ->orderBy('menugroup''asc')
        ->orderBy('menuid',    'asc')
        ->get();
        return view('settings.menuroles.index', ['data' => $data]);
    }

    public function create(){
        $data = DB::table('menugroups')->get();
        return view('settings.menuroles.create', ['groups' => $data]);
    }

    public function save(Request $request){
        DB::beginTransaction();
        try{
            $output = array();
            $menuid = $request['itm_idmenu'];
            for($i = 0$i < sizeof($menuid); $i++){
                $menuroledata = array(
                    'menuid'    => $menuid[$i],
                    'roleid'    => $request['roleid']
                );
                array_push($output$menuroledata);
            }
            insertOrUpdate($output,'menuroles');
            DB::commit();
            return Redirect::to("/setting/menuroles")->withSuccess('New Menu Role Created');
        }catch(\Exception $e){
            DB::rollBack();
            return Redirect::to("/setting/menuroles")->withError($e->getMessage());
        }
    }
}

php artisan make:controller Setting\UserRoleController
<?php

namespace App\Http\Controllers\Setting;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

use Validator,Redirect,Response;
use DB;

class UserRoleController extends Controller
{
    public function index(){
        $data = DB::table('v_userroles')->get();
        return view('settings.userroles.index', ['data' => $data]);
    }

    public function create(){
        $data = DB::table('menugroups')->get();
        return view('settings.userroles.create', ['groups' => $data]);
    }

    public function save(Request $request){
        // return $request;
        DB::beginTransaction();
        try{
            $output = array();
            $roleid = $request['itm_roleid'];
            for($i = 0$i < sizeof($roleid); $i++){
                $menuroledata = array(
                    'email'     => $request['email'],
                    'roleid'    => $roleid[$i]
                );
                array_push($output$menuroledata);
            }
            insertOrUpdate($output,'userroles');
            DB::commit();
            return Redirect::to("/setting/userroles")->withSuccess('New User Role Created');
        }catch(\Exception $e){
            DB::rollBack();
            return Redirect::to("/setting/userroles")->withError($e->getMessage());
        }
    }

    public function delete($email$role){
        DB::beginTransaction();
        try{
            DB::table('userroles')->where('email'$email)->where('roleid'$role)->delete();
            DB::commit();
            return Redirect::to("/setting/userroles")->withSuccess('User Role Deleted');
        }catch(\Exception $e){
            DB::rollBack();
            return Redirect::to("/setting/userroles")->withError($e->getMessage());
        }
    }
}


Setelah semua controller dibuat, selanjutnya tambahkan middleware

php artisan make:middleware CheckAuth
<?php

namespace App\Http\Middleware;

use Illuminate\Support\Facades\Auth;
use Closure;
use DB;

use Illuminate\Http\Request;

class CheckAuth
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $requestClosure $next$path)
    {
        // return $next($request);
        if(Auth::user() === null){
            return redirect('/')->with(['error''Please login']);
        }

        $routeAuth = DB::table('v_usermenus')
            ->where('email'Auth::user()->email)
            ->where('route'$path)
            ->first();
        
        if(empty($routeAuth)){
            return redirect('/')->with(['error''Opps! You do not have access']);
        }

        return $next($request);
    }
}

middleware ini digunakan untuk mengecek apakah user bisa mengakses menu yang dipilih atau tidak.

php artisan make:middleware RevalidateBackHistory
<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class RevalidateBackHistory
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $requestClosure $next)
    {
        // return $next($request);
        $response = $next($request);
        
        return $response->header('Cache-Control','nocache, no-store, max-age=0, must-revalidate')
            ->header('Pragma','no-cache')
            ->header('Expires','Fri, 01 Jan 1999 00:00:00 GMT');
    }
}

setelah kedua middleware dibuat, selanjutnya registrasi middleware nya pada file Kernel.php


<?php

namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
    /**
     * The application's global HTTP middleware stack.
     *
     * These middleware are run during every request to your application.
     *
     * @var array
     */
    protected $middleware = [
        // \App\Http\Middleware\TrustHosts::class,
        \App\Http\Middleware\TrustProxies::class,
        \Fruitcake\Cors\HandleCors::class,
        \App\Http\Middleware\PreventRequestsDuringMaintenance::class,
        \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
        \App\Http\Middleware\TrimStrings::class,
        \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
    ];

    /**
     * The application's route middleware groups.
     *
     * @var array
     */
    protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            // \Illuminate\Session\Middleware\AuthenticateSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],

        'api' => [
            // \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
            'throttle:api',
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],
    ];

    /**
     * The application's route middleware.
     *
     * These middleware may be assigned to groups or used individually.
     *
     * @var array
     */
    protected $routeMiddleware = [
        'auth' => \App\Http\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
        'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
        'revalidate' => \App\Http\Middleware\RevalidateBackHistory::class,
        'checkAuth'    => \App\Http\Middleware\CheckAuth::class,
    ];
}


selanjutnya tambahkan folder baru didalam folder app denga nama Helpers, lalu didalamnya tambahkan file baru dengan nama helpers.php 

<?php

use Illuminate\Support\Facades\DB;

function userMenu(){
    $mnGroups = DB::table('v_usermenus')
                ->select('menugroup''groupname''groupicon')
                ->distinct()
                ->where('email'Auth::user()->email)
                ->get();
    return $mnGroups;
}

function userSubMenu(){
    $mnGroups = DB::table('v_usermenus')
                ->select('menugroup''route''menuname')
                ->distinct()
                ->where('email'Auth::user()->email)
                ->get();
    return $mnGroups;
}

function insertOrUpdate(array $rows$table){
    $first = reset($rows);

    $columns = implode(
        ',',
        array_map(function ($value) {
            return "$value";
        }, array_keys($first))
    );

    $values = implode(','array_map(function ($row) {
            return '('.implode(
                ',',
                array_map(function ($value) {
                    return '"'.str_replace('"''""'$value).'"';
                }, $row)
            ).')';
    }, $rows));

    $updates = implode(
        ',',
        array_map(function ($value) {
            return "$value = VALUES($value)";
        }, array_keys($first))
    );

    $sql = "INSERT INTO {$table}({$columns}) VALUES {$valuesON DUPLICATE KEY UPDATE {$updates}";

    return \DB::statement($sql);
}

function testHelper(){
    return "A";
}


setelah helpers dibuat, registrasi helpers pada file composer.json dibagian autoload seperti berikut :



Lalu untuk step selanjutnya pada postingan berikut nya 

https://husnulmshare.blogspot.com/2021/09/laravel-8-user-management-part3.html

Comments

  1. dari tahapan 2 sampai 4 eror pada saat membuat view di db mohon bantunya kk

    ReplyDelete
    Replies
    1. halo, kalau boleh tau errornya apa?

      Delete
    2. This comment has been removed by the author.

      Delete
  2. This comment has been removed by the author.

    ReplyDelete
  3. This comment has been removed by the author.

    ReplyDelete
  4. public function save(Request $request,)
    {
    // return $request;
    DB::beginTransaction();
    try {
    $output = array();
    $roleid = $request['itm_roleid'];
    for ($i = 0; $i < sizeof($roleid); $i++) {
    $menuroledata = array(
    'email' => $request['email'],
    'roleid' => $roleid[$i]
    );
    array_push($output, $menuroledata);
    }
    insertOrUpdate($output, 'userroles');
    DB::commit();
    return Redirect()->to("/setting/userroles")->withSuccess('New User Role Created');
    } catch (\Exception $e) {
    DB::rollBack();
    return Redirect()->to("/setting/userroles")->withError($e->getMessage());
    }
    }

    pada bagian insertOrUpdate kok bisa eror kk?

    ReplyDelete
  5. boleh minta file .sql yg ada recordnya min untuk referensi

    ReplyDelete
    Replies
    1. Silahkan download disini

      https://drive.google.com/file/d/1xhB9f-3raI_1B06GPs1QFtaZ4fpclUQi/view?usp=sharing

      Delete
  6. bisa mintak file.sql nya kk untuk media pembelajaran ?

    ReplyDelete
    Replies
    1. silahkan download disini

      https://drive.google.com/file/d/1xhB9f-3raI_1B06GPs1QFtaZ4fpclUQi/view?usp=sharing

      Delete
    2. This comment has been removed by the author.

      Delete
  7. maaf kk mengganggu, untuk file data base hampir semua korup kk jadi gak bisa di buka kk, bisa minta tolong untuk data sql nya kk, terimakasih

    ReplyDelete

Post a Comment

Popular posts from this blog

PHP MySql CRUD Dengan Konsep MVC

Laravel - Sistem Informasi Perpustakaan Sederhana Laravel

IT Asset Management Dengan PHP MySQL