Wednesday, 2 December 2020

Roles and Permission Full project

 

Roles and Permission

1. Install the package via composer.
composer require spatie/laravel-permission

2. add the service provider in your config/app.php file:
'providers' => [
    Spatie\Permission\PermissionServiceProvider::class,
];

3. You should publish the migration and the config/permission.php config file with.
php artisan vendor:publish --provider="Spatie\Permission\PermissionServiceProvider"

4. Run the artisan command to clear the cache.
php artisan optimize:clear
 # or
php artisan config:clear

5. Run the migrations. php artisan migrate

6. First, add the Spatie\Permission\Traits\HasRoles trait to your User model(s)
use Illuminate\Foundation\Auth\User as Authenticatable;
use Spatie\Permission\Traits\HasRoles;

class User extends Authenticatable
{
    use HasRoles;
}

7. Create 2 models named ModelHasRole and RoleHasPermission
php artisan make:model ModelHasRole

use Spatie\Permission\Traits\HasRoles;
class ModelHasRole extends Model
{
    use HasRoles;
    public $table = 'model_has_roles';
    public $timestamps = false;   
}

php artisan make:model RoleHasPermission
class RoleHasPermission extends Model
{    
    public $table = 'role_has_permissions';
    public $timestamps = false;
    protected $fillable = ['permission_id','role_id',];    
}
Update User Model

use Spatie\Permission\Traits\HasRoles;
class User extends Authenticatable
{
    use Notifiable; use HasRoles;
.....
}

8. Create 3 controller name PermissionController , RolesController and UsersController

###################PermissionController.php###################
PermissionController

<?php
 
namespace App\Http\Controllers;
 
use App\Http\Controllers\Controller;

use App\User; use Hash; use Validator;
use Auth; use DB; use Session;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
use DataTables;
use App\Http\Requests\PermissionRequest;
use Spatie\Permission\Models\Permission;

class PermissionsController extends Controller
{    
    public function __construct()  {  $this->middleware(['auth']);   }

    public function index(Request $request)
    {
        if ($request->ajax()) {
            $data = DB::table('permissions')->select(['id', 'name'])->get();
            return Datatables::of($data)            
            ->addColumn('action', function ($data)
          {           
            $btn = '<a href="permissions/show/'.  $data->id .'" class="btn btn-primary btn-sm"> <i class="fas fa-folder"></i> View</a> ';
            $btn = $btn. '<a href="permissions/edit/'.  $data->id .'" class="btn btn-info btn-sm"> <i class="fas fa-pencil-alt"></i> Edit</a> ';
            $btn = $btn. '<a href="permissions/delete/'.$data->id .'" class="btn btn-danger btn-sm"> <i class="fas fa-trash"></i> Delete</a>';
            return $btn;
            })              
            ->rawColumns(array("action", "st"))
            ->make(true);
        }      
         return view('permissions.index', compact('permissions'));
    }

    public function create()
    {               
        return view('permissions.create');
    }
    
   public function store(PermissionRequest $request)
    {
       $validator = $request->validated();
       $name = $request->name;             
               
       Permission::create(['name' => $name]);             
       toastr()->success('Sucessfully inserted!');
       return redirect('permissions');        
    }
    
    public function show(Request $request)
    {
      $uid = $request->id;
      $data_array =  DB::table('permissions')->where('id', '=', $uid)->get();
      return view('permissions.show',['data_array' => $data_array]);
    }   
    
    public function edit(Request $request)
    {
      $uid = $request->id;
      $data_array =  DB::table('permissions')->where('id', '=', $uid)->get();
      return view('permissions.edit',['data_array' => $data_array]);
    }
    
    public function update(Request $request)
    {   $postData = $request->all();            
        $messages = array('name.required'=>'You cant leave name field empty',);
        $rules = array('name'=>'required | min:5',);  
        $validator = Validator::make($postData, $rules,$messages);  
     
        if($validator->fails()) { 
           toastr()->error('Error occured!');
           return redirect()->back()->withErrors($validator)->withInput();     
         }else {      
               
         $name = $request->name;
         $id = $request->id;         
         
        if (Permission::where('name', '=', $name)->exists())
         {
           $messages = array('name'=>'Already exist',);                   
           return redirect()->back()->withErrors($messages)->withInput();           
         } else {             
           $updated = DB::table('permissions')->where('id',$id)->update(['name' => $name]);
           if($updated  > 0 )
            {                     
             toastr()->success('Sucessfully updated!');
             return redirect('permissions');  
            } else {      
             toastr()->error('Error occured!');
             return redirect('permissions');
           }
        } // if ends here.        
       } // if validate ends here.   
    }
    
    public function delete(Request $request,$id)
    {       
        $id = $request->id;
        $deletedRows = DB::table('permissions')->where('id', '=', $id)->delete();
        if($deletedRows  > 0 )
        {          
           toastr()->success('Sucessfully deleted!');
           return redirect('permissions');  
        } else {
            toastr()->error('Error occured!');
            return redirect('permissions');  
        }
    }
}

###################PermissionRequest.php########################
php artisan make:request PermissionController

<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;

class PermissionRequest extends FormRequest
{
    public function authorize()
    {
        return true;
    }
    public function rules()
    {
       return [ 'name' => 'required | min: 5  | unique:permissions'];
    }   
    public function messages() {
        return [
            'name.required' => 'Name cannot be blank.',
            'name.min' => 'Name cannot be less than 5 blank.',
            'name.unique' => 'Name already exist'
         ];
    }
}
###################RolesController.php########################

php artisan make:controller RolesController

<?php
 
namespace App\Http\Controllers;
 
use App\Http\Controllers\Controller;
use App\User; use Hash; use Validator;
use Auth; use DB; use Session;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
use DataTables;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;
use App\RoleHasPermission;
use App\Http\Requests\RoleRequest;

class RolesController extends Controller
{    
    public function __construct()  {  $this->middleware(['auth']);   }
     public function index(Request $request)
    {
        if ($request->ajax()) {
            $data =  Role::all();//Get all roles
             return Datatables::of($data)                        
             
            ->addColumn('action', function ($data)
            {           
                $btn = '<a href="roles/show/'.  $data->id .'" class="btn btn-primary btn-sm">
                <i class="fas fa-folder"></i> View</a> ';
                $btn = $btn. '<a href="roles/edit/'.  $data->id .'" class="btn btn-info btn-sm">
                <i class="fas fa-pencil-alt"></i> Edit</a> ';
                $btn = $btn. '<a href="roles/delete/'.$data->id .'" class="btn btn-danger btn-sm">
                <i class="fas fa-trash"></i> Delete</a>';
                return $btn;
            })
            ->addColumn('permission', function ($data)
            {
                $role = $data->findByName($data->name);
                 $permission = $role->getPermissionNames();
                $clean1 = str_replace('"','',$permission);
                $clean2 = str_replace('[]','',$clean1);                 
                return $clean2;
            })                        
            ->rawColumns(array("action","permission"))
            ->make(true);
        }      
         return view('roles.index');
    }

    public function create()
    {   $permissions = DB::table('permissions')->select(['id', 'name'])->get();               
        return view('roles.create',['data_array' => $permissions]);
    }
    
   public function store(RoleRequest $request)
    {    
           $validator = $request->validated();
           $name = $request->name;          
           $role = Role::create(['name' => $request->input('name')]);
           $role->syncPermissions($request->input('permission'));                        
           toastr()->success('Sucessfully inserted!');
           return redirect('roles');  
    }
    
    public function show(Request $request)
    {
      $uid = $request->id;
      $role = Role::find($uid);
      $rolePermissions = Permission::join("role_has_permissions","role_has_permissions.permission_id","=","permissions.id")
      ->where("role_has_permissions.role_id",$uid)
      ->get();
      return view('roles.show',compact('role','rolePermissions'));   
    }   
    
    public function edit(Request $request)
    {     
      $uid = $request->id;
      $role = Role::findOrFail($uid);
      $rolehpermissions = $role->getPermissionNames();    
      $permissions = Permission::all();           
      $roles =  DB::table('roles')->where('id', '=', $uid)->get();   
      return view('roles.edit',['roles' => $roles, 'permissions' => $permissions, 'rolehpermissions' => $rolehpermissions]);     
    }
    
    public function update(Request $request)
    {    $postData = $request->all();            
        $messages = array('name.required'=>'You cant leave name field empty',);
        $rules = array('name'=>'required | min:4',);  
        $validator = Validator::make($postData, $rules,$messages);  
     
        if($validator->fails()) {
           toastr()->error('Error occured!');
           return redirect()->back()->withErrors($validator)->withInput();     
         }else {      
         
        if (!empty($request->permission)) {
         
        $id = $request->input('id');
        $role = Role::find($id);
        $role->name = $request->input('name');
        $role->save();
        $role->syncPermissions($request->input('permission'));      
           
         toastr()->success('Sucessfully updated!');
         return redirect('roles');
        } else {      
         toastr()->error('Error occured!');
         return redirect('roles');
       }          
           
       } // if validate ends here.   
    }
    
    public function delete(Request $request,$id)
    {       
        $id = $request->id;
        $deletedRows = DB::table('roles')->where('id', '=', $id)->delete();
        if($deletedRows  > 0 )
        {          
           toastr()->success('Sucessfully deleted!');
           return redirect('roles');  
        } else {
            toastr()->error('Error occured!');
            return redirect('roles');  
        }
    }
}
###################RoleRequest.php########################

php artisan make:request RoleRequest

<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;

class RoleRequest extends FormRequest
{
   public function rules()
    {
       return [ 'name' => 'required | min: 5  | unique:roles'];
    }   
    public function messages() {
        return [
            'name.required' => 'Name cannot be blank.',
            'name.min' => 'Name cannot be less than 5 blank.',
            'name.unique' => 'Name already exist'
         ];
    }
}

###################UsersController.php########################

php artisan make:controler UsersController

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Auth; use DB;
use Excel; use PDF;
use App\User;
use App\Exports\UserExport;
use DataTables;
use Spatie\Permission\Models\Role;

class UserController extends Controller
{  public function __construct()  {  $this->middleware(['auth']);   }
    
    public function index(Request $request)
    {
        if ($request->ajax())
         {
            $data =  User::select(['id', 'name', 'email', 'status'])->get();   
            return Datatables::of($data)
           
            ->addColumn('action', function ($data) {           
            $btn = '<a href="user/show/'.  $data->id .'" class="btn btn-primary btn-sm"> <i class="fas fa-folder"></i> View</a> ';
            $btn = $btn. '<a href="user/edit/'.  $data->id .'" class="btn btn-info btn-sm"> <i class="fas fa-pencil-alt"></i> Edit</a> ';
            $btn = $btn. '<a href="user/delete/'.$data->id .'" class="btn btn-danger btn-sm"> <i class="fas fa-trash"></i> Delete</a>';
            return $btn;
            })
           
            ->addColumn('roles', function ($data) {   
            $user = User::find($data->id);
            $assignedroles =  $user->getRoleNames();       
            $clean1 = str_replace('"','',$assignedroles);
            $clean2 = str_replace('[]','',$clean1);
             $roles = $clean2;               
            return $roles;
            })
           
            ->addColumn('st', function ($data) {
            if($data->status==0) {
            $status = "Inactive";
                } else {
            $status = "Active";
                }
                return $status;
            })
                      
            ->rawColumns(array("action", "st" ,'roles'  ))
            ->make(true);
        }      
         return view('users.index', compact('users'));
    }
    
    public function edit(Request $request)
    {
        $uid = $request->id;
        $data_array =  DB::table('users')->where('id', '=', $uid)->get();
        $roles =  Role::all();
       
        $user = User::find($uid);
        $assignedroles =  $user->roles;              
        return view('users.edit', compact('data_array','roles','assignedroles'));
    }

    public function update(Request $request)    
    {
        $user = new User;         
        $id = $request->id;   
        $name = $request->name;   
        $email = $request->email;   
        $status = $request->status;       
                
        $updated = DB::table('users')
        ->where('id', $id)
        ->update(['name' => $name,'email' => $email,'status' => $status,'updated_at' => now()]);
          
        if($updated  > 0 )
        {                     
         toastr()->success('Sucessfully updated!');
         return redirect('user'); 
        } else {      
         toastr()->error('Error occured!');
         return redirect('user');
       }          
         
    }
    
    public function updateroles(Request $request)   
     {       
        $id = $request->id;   
        $user = User::find($id);   
         
        DB::table('model_has_roles')->where('model_id',$id)->delete();   
        $user->syncRoles($request->input('role'));
                 
        toastr()->success('Sucessfully updated!');
        return redirect('user');          
    }
    
    public function delete(Request $request,$id)
    {       
        $id = $request->id;
        $deletedRows = DB::table('users')->where('id', '=', $id)->delete();
        if($deletedRows  > 0 )
        {         
           toastr()->success('Sucessfully deleted!');
           return redirect('user'); 
        } else {
           toastr()->error('Error occured!');
           return redirect('user'); 
        }
    }
    
    public function show(Request $request)
    {
        $uid = $request->id;
        $data_array =  DB::table('users')->where('id', '=', $uid)->get();    
        $user = User::find($uid);
        $assignedroles =  $user->roles; 
        return view('users.show',compact('data_array','assignedroles'));
    }
       
    public function downloaduserpdf()
    {   
        $data_arrays = DB::table('users')->orderBy('id', 'asc')->get();          
        $pdf = PDF::loadView('users.downloaduserpdf',['data_arrays' => $data_arrays]);
        return $pdf->download('User.pdf');
    }
    
    public function downloaduserxls()
    {
         return new UserExport();
    }
    
    public function profile()
    {  
        $id= \Auth::guard('web')->user()->id;
         $profile = DB::table('users')->where('id','=',$id)->get();
        return view('admin.profile.profile',['profile' => $profile]);
     }
    
    public function editprofile(Request $request)
    {
        $user = new User;         
        $id = $request->id;   
        $name = $request->name;   
        $email = $request->email;   
        $password = Hash::make($request->password);
       
        $updated = DB::table('users')
           ->where('id', $id)
           ->update(['name' => $name,'email' => $email,'password' => $password,'updated_at' => now()]);
       
       
        if($updated  > 0 )
        {                     
        toastr()->success('Sucessfully updated!');
        return redirect('/admin'); 
        } else {      
        toastr()->error('Error occured!');
        return redirect('admin/profile');
        }          
      }

    public function create()
    {
        $data_array = DB::table('roles')->orderBy('id', 'desc')->get();         
        return view('admin.users.create', compact('data_array'));
    }

    public function store(Request $request)
    {  
        $postData = $request->all();                   
        $messages = array('name.required'=>'You cant leave name field empty',);
        $rules = array('name'=>'required | min:4');  
        $rules = array('email'=>'required | email');
        $rules = array('password'=>'required | min:4');
        $validator = Validator::make($postData, $rules,$messages);  
     
        if($validator->fails()) { 
           toastr()->error('Error occured!');
           return redirect()->back()->withErrors($validator)->withInput();     
         }else {      
      
        $user = new User;
        $name = $request->name;
        $email = $request->email;         
        $password = $request->request->set('password', Hash::make($request->password));
        $user = User::create($request->all());
 
        $user->roles()->sync($request->input('roles', []));
          toastr()->success('Sucessfully inserted!');
          return redirect('admin/users');
        } // if validate ends here.
     }
 
    public function user_status(Request $request)
    {     
        $uid    = $request->userid;
        $status = $request->status;
       
        if ($status == '1') {
            $user_status = DB::table('users')->where('id', $uid)->update(['status'=>0] );      
        } else if ($status == '0') {
            $user_status = DB::table('users')->where('id', $uid)->update(['status'=>1] );
        }
        return $user_status;
  }
}

#############################UserExport.php######################################
<?php

namespace App\Exports;
use Illuminate\Database\Eloquent\Model;

use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\Exportable;
use Illuminate\Contracts\Support\Responsable;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithProperties;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
use Maatwebsite\Excel\Concerns\WithStyles;
use DB;

 class UserExport implements FromCollection,WithHeadings,WithProperties,Responsable,
 ShouldAutoSize,WithStyles
  {   
   use Exportable;
   
    public function collection()
    {
         return DB::table('users')->select('id','name','email','status')->orderBy('id', 'asc')->get();       
    }
    
    public function headings(): array
    {
        return [
            'ID',
            'Name',
            'Email',
            'Status',            
        ];
    }
    
    public function properties(): array
    {
        return [
            'creator'        => 'Ramesh Yadav',
            'title'          => 'User List',
        ];
    }
    
    private $fileName = 'UserList.xlsx';
    private $headers = ['Content-Type' => 'text/csv',];
    
     public function styles(Worksheet $sheet)
    {
        return [
            // Style the first row as bold text.
            1    => ['font' => ['bold' => true]],
     
            // Styling an entire column.
            '1'  => ['font' => ['size' => 11]],
        ];
    }

}

#############################Route.php##########################################
9. Route  
// Permissions ============================================================
Route::get('/permissions','PermissionsController@index')->name('permissions.index');    
Route::get('/permissions/create','PermissionsController@create')->name('permissions.create');    
Route::post('/permissions/store','PermissionsController@store')->name('permissions.store');    
Route::get('/permissions/show/{id}','PermissionsController@show')->name('permissions.show');
Route::get('/permissions/edit/{id}','PermissionsController@edit')->name('permissions.edit');
Route::post('/permissions/update','PermissionsController@update')->name('permissions.update');
Route::get('/permissions/delete/{id}','PermissionsController@delete')->name('permissions.delete');    
// Roles  ================================================================   
Route::get('/roles','RolesController@index')->name('roles.index');    
Route::get('/roles/create','RolesController@create')->name('roles.create');
Route::post('/roles/store','RolesController@store')->name('roles.store');
Route::get('/roles/show/{id}','RolesController@show')->name('roles.show');
Route::get('/roles/edit/{id}','RolesController@edit')->name('roles.edit');
Route::post('/roles/update','RolesController@update')->name('roles.update');
Route::get('/roles/delete/{id}','RolesController@delete')->name('roles.delete');    

// Users ===========================================================
Route::get('/user', 'UserController@index')->name('index');
Route::get('/user/downloaduserxls','UserController@downloaduserxls')->name('user.downloaduserxls');    
Route::get('/user/downloaduserpdf','UserController@downloaduserpdf')->name('user.downloaduserpdf');    
Route::get('/user/show/{id}','UserController@show')->name('user.show');
Route::get('/user/edit/{id}','UserController@edit')->name('user.edit');
Route::post('/user/update','UserController@update')->name('user.update');
Route::post('/user/updateroles','UserController@updateroles')->name('user.updateroles');
Route::get('/user/delete/{id}','UserController@delete')->name('user.delete');

Now add Permission, Roles and Users View files that include [ index, edit, update, show ]


#############################Permission index.blade.php##########################
@extends('layouts.frontend')
@section('css')
<style>
tfoot { display: table-header-group; } table.dataTable input:nth-child(1) { width:100%; }
</style>
<link rel="stylesheet" href="{{ asset('public/admin/plugins/datatables-bs4/css/dataTables.bootstrap4.min.css') }}">
<link rel="stylesheet" href="{{ asset('public/admin/plugins/datatables-responsive/css/responsive.bootstrap4.min.css') }}">
@endsection
@section('content')
<div class="content-wrapper">
  <!-- Content Header (Page header) -->
  <section class="content-header">
    <div class="container-fluid">
      <div class="row mb-2">
        <div class="col-sm-6">
          <h1>Permissions</h1>
        </div>
        <div class="col-sm-6">
          <ol class="breadcrumb float-sm-right">
            <li class="breadcrumb-item"><a href="{{url('home')}}">Home</a></li>
            <li class="breadcrumb-item active">Permissions</li>
          </ol>
        </div>
      </div>
    </div>
    <!-- /.container-fluid -->
  </section>
  <!-- Main content -->
  <section class="content">
    <div class="container-fluid">
      <div class="row">
        <div class="col-12">
          <!-- Default box -->
          <div class="card">
            <div class="card-header">
              <h3 class="card-title">Permissions Listing</h3>
              <div class="card-tools"> <a href="{{url('permissions/create')}}" class="btn btn-primary btn-sm">Create New Permission</a> | <a href="{{url('permissions/downloaduserpdf')}}">Download PDF</a> | <a href="{{url('permissions/downloaduserxls')}}">Download XLS</a>
                <button type="button" class="btn btn-tool" data-card-widget="collapse" data-toggle="tooltip" title="Collapse"> <i class="fas fa-minus"></i></button>
                <button type="button" class="btn btn-tool" data-card-widget="remove" data-toggle="tooltip" title="Remove"> <i class="fas fa-times"></i></button>
              </div>
            </div>
            <div class="card-body">
              <table class="table table-bordered yajra-datatable">
                <thead>
                  <tr>
                    <th>Id</th>
                    <th>Name</th>
                    <th>Action</th>
                  </tr>
                </thead>
                <tfoot>
                  <tr>
                    <th>Id</th>
                    <th>Name</th>
                    <th hidden>Action</th>
                  </tr>
                </tfoot>
              </table>
            </div>
            <!-- /.card-body -->
          </div>
          <!-- /.card -->
        </div>
      </div>
    </div>
  </section>
  <!-- /.content -->
</div>
@endsection
@section('script')
<script type="text/javascript">

$(document).ready(function(){
var table = $('.yajra-datatable').DataTable({
        processing: true,
        serverSide: true,
        ajax: "{{ url('permissions') }}",
        columns: [           
            {data: 'id',   name: 'id'},
            {data: 'name', name: 'name'},                      
            {data: 'action', name: 'action', orderable: false, searchable: false}
        ],               
        initComplete: function () {
        this.api().columns().every(function () {
            var column = this;
            var input = document.createElement("input");
            $(input).appendTo($(column.footer()).empty())
            .on('change', function () {
                column.search($(this).val(), false, false, true).draw();
            });
        });
    }
 });
});  
</script>
<script src="{{ asset('public/admin/plugins/datatables/jquery.dataTables.min.js') }}"></script>
<script src="{{ asset('public/admin/plugins/datatables-bs4/js/dataTables.bootstrap4.min.js') }}"></script>
<script src="{{ asset('public/admin/plugins/datatables-responsive/js/dataTables.responsive.min.js') }}"></script>
<script src="{{ asset('public/admin/plugins/datatables-responsive/js/responsive.bootstrap4.min.js') }}"></script>
@endsection

#############################Permission create.blade.php#########################
@extends('layouts.frontend')
@section('css')
@endsection
@section('content')
<div class="content-wrapper">
  <!-- Content Header (Page header) -->
  <section class="content-header">
    <div class="container-fluid">
      <div class="row mb-2">
        <div class="col-sm-6">
          <h1>Permissions</h1>
        </div>
        <div class="col-sm-6">
          <ol class="breadcrumb float-sm-right">
            <li class="breadcrumb-item"><a href="{{url('home')}}">Home</a></li>
            <li class="breadcrumb-item"><a href="{{url('permissions')}}">Permissions</a>
            <li class="breadcrumb-item active">Permissions Create</li>
          </ol>
        </div>
      </div>
    </div>
    <!-- /.container-fluid -->
  </section>
  <!-- Main content -->
  <section class="content">
    <div class="container-fluid">
      <div class="row">
        <div class="col-12">
          <!-- Default box -->
          <div class="card">
            <div class="card-header">
              <h3 class="card-title">Permissions Create</h3>
              <div class="card-tools">
                <button type="button" class="btn btn-tool" data-card-widget="collapse" data-toggle="tooltip" title="Collapse"> <i class="fas fa-minus"></i></button>
                <button type="button" class="btn btn-tool" data-card-widget="remove" data-toggle="tooltip" title="Remove"> <i class="fas fa-times"></i></button>
              </div>
            </div>
            <div class="card-body">
              <form method="POST" action="{{route('permissions.store')}}" enctype="multipart/form-data">
                @csrf
                <div class="row">
                  <div class="col-sm-6">
                    <div class="form-group">
                      <label class="required" for="title">Permissions Name <span class="text-danger">*</span></label>
                      <input class="form-control {{ $errors->has('name') ? 'is-invalid' : '' }}" type="text" name="name" id="name"  value="" required>
                      @if($errors->has('name')) <span class="text-danger">{{ $errors->first('name') }}</span> @endif </div>
                  </div>
                </div>
                <div class="row">
                  <div class="col-md-6">
                    <div class="form-group">
                      <button class="btn btn-success" type="submit">Update </button>
                      <input class="btn btn-danger" action="action" onclick="window.history.go(-1); return false;" type="submit" value="Cancel"/>
                    </div>
                  </div>
                </div>
              </form>
            </div>
            <!-- /.card-body -->
          </div>
          <!-- /.card -->
        </div>
      </div>
    </div>
  </section>
  <!-- /.content -->
</div>
@endsection

#############################Permission edit.blade.php###########################
@extends('layouts.frontend')
@section('css')
@endsection
@section('content')
<div class="content-wrapper">
  <!-- Content Header (Page header) -->
  <section class="content-header">
    <div class="container-fluid">
      <div class="row mb-2">
        <div class="col-sm-6">
          <h1>Permissions</h1>
        </div>
        <div class="col-sm-6">
          <ol class="breadcrumb float-sm-right">
            <li class="breadcrumb-item"><a href="{{url('home')}}">Home</a></li>
            <li class="breadcrumb-item"><a href="{{url('permissions')}}">Permissions</a>
            <li class="breadcrumb-item active">Permissions Show</li>
          </ol>
        </div>
      </div>
    </div>
    <!-- /.container-fluid -->
  </section>
  <!-- Main content -->
  <section class="content">
    <div class="container-fluid">
      <div class="row">
        <div class="col-12">
          <!-- Default box -->
          <div class="card">
            <div class="card-header">
              <h3 class="card-title">Permissions Show</h3>
              <div class="card-tools">
                <button type="button" class="btn btn-tool" data-card-widget="collapse" data-toggle="tooltip" title="Collapse"> <i class="fas fa-minus"></i></button>
                <button type="button" class="btn btn-tool" data-card-widget="remove" data-toggle="tooltip" title="Remove"> <i class="fas fa-times"></i></button>
              </div>
            </div>
            <div class="card-body">
              <form method="POST" action="{{route('permissions.update')}}" enctype="multipart/form-data">
                @csrf
                <?php $cnt = count($data_array); if ($cnt>0) {?>
                @foreach($data_array as $key =>  $data_array)
                <div class="row">
                  <div class="col-sm-6">
                    <div class="form-group">
                      <label class="required" for="title">Permissions Name <span class="text-danger">*</span></label>
                      <input class="form-control {{ $errors->has('name') ? 'is-invalid' : '' }}" type="text" name="name" id="name"  value="{{$data_array->name}}" required>
                      @if($errors->has('name')) <span class="text-danger">{{ $errors->first('name') }}</span> @endif </div>
                  </div>
                </div>
                @endforeach
                <?php } else { ?>
                <p>Record not found.</p>
                <?php } ?>
                <div class="row">
                  <div class="col-md-6">
                    <div class="form-group">
                      <input type="hidden" name="id" id="id" value="{{$data_array->id}}" >
                      <button class="btn btn-success" type="submit">Update </button>
                      <input class="btn btn-danger" action="action" onclick="window.history.go(-1); return false;" type="submit" value="Cancel"/>
                    </div>
                  </div>
                </div>
              </form>
            </div>
            <!-- /.card-body -->
          </div>
          <!-- /.card -->
        </div>
      </div>
    </div>
  </section>
  <!-- /.content -->
</div>
@endsection

#############################Permission show.blade.php##########################
@extends('layouts.frontend')
@section('content')
<div class="content-wrapper">
  <!-- Content Header (Page header) -->
  <section class="content-header">
    <div class="container-fluid">
      <div class="row mb-2">
        <div class="col-sm-6">
          <h1>Permissions</h1>
        </div>
        <div class="col-sm-6">
          <ol class="breadcrumb float-sm-right">
            <li class="breadcrumb-item"><a href="{{url('home')}}">Home</a></li>
            <li class="breadcrumb-item"><a href="{{url('permissions')}}">Permissions</a>
            <li class="breadcrumb-item active">Permissions Edit</li>
          </ol>
        </div>
      </div>
    </div>
    <!-- /.container-fluid -->
  </section>
  <!-- Main content -->
  <section class="content">
    <div class="container-fluid">
      <div class="row">
        <div class="col-12">
          <!-- Default box -->
          <div class="card">
            <div class="card-header">
              <h3 class="card-title">Permissions Show</h3>
              <div class="card-tools">
                <button type="button" class="btn btn-tool" data-card-widget="collapse" data-toggle="tooltip" title="Collapse"> <i class="fas fa-minus"></i></button>
                <button type="button" class="btn btn-tool" data-card-widget="remove" data-toggle="tooltip" title="Remove"> <i class="fas fa-times"></i></button>
              </div>
            </div>
            <div class="card-body">
              <table class="table table-bordered data-table">
                <thead>
                  <?php $cnt = count($data_array); if ($cnt>0) {?>
                @foreach($data_array as $key =>  $data_array)
                <tr>
                  <th width="150px"><strong>Id</strong></th>
                  <th>{{$data_array->id}}</th>
                </tr>
                <tr>
                  <th width="150px"><strong>Name</strong></th>
                  <th>{{$data_array->name}}</th>
                </tr>
                <tr> @endforeach
                  <?php } else { ?>
                <tr>
                  <td colspan="2"><p>Record not found.</p></td>
                </tr>
                <?php } ?>
                <th colspan="2" align="center"><input class="btn btn-danger" action="action" onclick="window.history.go(-1); return false;" type="submit" value="Back"/></th>
                  </thead>
              </table>
            </div>
            <!-- /.card-body -->
          </div>
          <!-- /.card -->
        </div>
      </div>
    </div>
  </section>
  <!-- /.content -->
</div>
@endsection

#############################Role index.blade.php###############################
@extends('layouts.frontend')
@section('css')
<style>
tfoot { display: table-header-group; } table.dataTable input:nth-child(1) { width:100%; }
</style>
<link rel="stylesheet" href="{{ asset('public/admin/plugins/datatables-bs4/css/dataTables.bootstrap4.min.css') }}">
<link rel="stylesheet" href="{{ asset('public/admin/plugins/datatables-responsive/css/responsive.bootstrap4.min.css') }}">
@endsection
@section('content')
<div class="content-wrapper">
  <!-- Content Header (Page header) -->
  <section class="content-header">
    <div class="container-fluid">
      <div class="row mb-2">
        <div class="col-sm-6">
          <h1>Roles</h1>
        </div>
        <div class="col-sm-6">
          <ol class="breadcrumb float-sm-right">
            <li class="breadcrumb-item"><a href="{{url('home')}}">Home</a></li>
            <li class="breadcrumb-item active">Roles</li>
          </ol>
        </div>
      </div>
    </div>
    <!-- /.container-fluid -->
  </section>
  <!-- Main content -->
  <section class="content">
    <div class="container-fluid">
      <div class="row">
        <div class="col-12">
          <!-- Default box -->
          <div class="card">
            <div class="card-header">
              <h3 class="card-title">Roles Listing</h3>
              <div class="card-tools"> <a href="{{url('roles/create')}}" class="btn btn-primary btn-sm">Create New Roles</a> | <a href="{{url('roles/downloaduserpdf')}}">Download PDF</a> | <a href="{{url('roles/downloaduserxls')}}">Download XLS</a>
                <button type="button" class="btn btn-tool" data-card-widget="collapse" data-toggle="tooltip" title="Collapse"> <i class="fas fa-minus"></i></button>
                <button type="button" class="btn btn-tool" data-card-widget="remove" data-toggle="tooltip" title="Remove"> <i class="fas fa-times"></i></button>
              </div>
            </div>
            <div class="card-body">
              <table class="table table-bordered yajra-datatable">
                <thead>
                  <tr>
                    <th>Id</th>
                    <th>Name</th>
                    <th>Permission</th>
                    <th>Action</th>
                  </tr>
                </thead>
                <tfoot>
                  <tr>
                    <th>Id</th>
                    <th>Name</th>
                    <th>Permission</th>
                    <th hidden>Action</th>
                  </tr>
                </tfoot>
              </table>
            </div>
            <!-- /.card-body -->
          </div>
          <!-- /.card -->
        </div>
      </div>
    </div>
  </section>
  <!-- /.content -->
</div>
@endsection
@section('script')
<script type="text/javascript">

$(document).ready(function(){
var table = $('.yajra-datatable').DataTable({
        processing: true,
        serverSide: true,
        ajax: "{{ url('roles') }}",
        columns: [           
            {data: 'id', },
            {data: 'name' },
            {data: 'permission' },               
            {data: 'action', orderable: false, searchable: false}
        ],
               
        initComplete: function () {
        this.api().columns().every(function () {
            var column = this;
            var input = document.createElement("input");
            $(input).appendTo($(column.footer()).empty())
            .on('change', function () {
                column.search($(this).val(), false, false, true).draw();
            });
        });
    }             
 });
});
</script>
<script src="{{ asset('public/admin/plugins/datatables/jquery.dataTables.min.js') }}"></script>
<script src="{{ asset('public/admin/plugins/datatables-bs4/js/dataTables.bootstrap4.min.js') }}"></script>
<script src="{{ asset('public/admin/plugins/datatables-responsive/js/dataTables.responsive.min.js') }}"></script>
<script src="{{ asset('public/admin/plugins/datatables-responsive/js/responsive.bootstrap4.min.js') }}"></script>
@endsection

#############################Role create.blade.php###############################
@extends('layouts.frontend')
@section('content')
<div class="content-wrapper">
  <!-- Content Header (Page header) -->
  <section class="content-header">
    <div class="container-fluid">
      <div class="row mb-2">
        <div class="col-sm-6">
          <h1>Roles</h1>
        </div>
        <div class="col-sm-6">
          <ol class="breadcrumb float-sm-right">
            <li class="breadcrumb-item"><a href="{{url('home')}}">Home</a></li>
            <li class="breadcrumb-item"><a href="{{url('roles')}}">Roles</a>
            <li class="breadcrumb-item active">Roles Create</li>
          </ol>
        </div>
      </div>
    </div>
    <!-- /.container-fluid -->
  </section>
  <!-- Main content -->
  <section class="content">
    <div class="container-fluid">
      <div class="row">
        <div class="col-12">
          <!-- Default box -->
          <div class="card">
            <div class="card-header">
              <h3 class="card-title">Roles Create</h3>
              <div class="card-tools">
                <button type="button" class="btn btn-tool" data-card-widget="collapse" data-toggle="tooltip" title="Collapse"> <i class="fas fa-minus"></i></button>
                <button type="button" class="btn btn-tool" data-card-widget="remove" data-toggle="tooltip" title="Remove"> <i class="fas fa-times"></i></button>
              </div>
            </div>
            <div class="card-body">
              <form method="POST" action="{{route('roles.store')}}" enctype="multipart/form-data">
                @csrf
                <div class="row">
                  <div class="col-sm-6">
                    <div class="form-group">
                      <label class="required" for="title">Roles Name <span class="text-danger">*</span></label>
                      <input class="form-control {{ $errors->has('name') ? 'is-invalid' : '' }}" type="text" name="name" id="name"  value="" required>
                      @if($errors->has('name')) <span class="text-danger">{{ $errors->first('name') }}</span> @endif </div>
                  </div>
                </div>
                <div class="row">
                  <div class="col-sm-6">
                    <div class="form-group">
                      <?php $cnt = count($data_array); if ($cnt>0) {?>
                      <label class="required" for="title">Permissions Name</label>
                      <br />
                      <div id="divCheckAll">
                        <input type="checkbox" name="checkall" id="checkall" onClick="check_uncheck_checkbox(this.checked);" />
                        Select / Deselect All </div>
                      <div class="form-group"> @foreach($data_array as $key =>  $data_array)
                        <input type="checkbox" value="{{ $data_array->id }}" name="permission[]" />
                        &nbsp;{{ $data_array->name }}
                        @endforeach
                        <?php } else { ?>
                        <p>Record not found.</p>
                        <?php } ?>
                      </div>
                    </div>
                  </div>
                </div>
                <div class="row">
                  <div class="col-md-6">
                    <div class="form-group">
                      <button class="btn btn-success" type="submit">Save</button>
                      <input class="btn btn-danger" action="action" onclick="window.history.go(-1); return false;" type="submit" value="Cancel"/>
                    </div>
                  </div>
                </div>
              </form>
            </div>
            <!-- /.card-body -->
          </div>
          <!-- /.card -->
        </div>
      </div>
    </div>
  </section>
  <!-- /.content -->
</div>
@endsection
<script>
function check_uncheck_checkbox(isChecked) {
    if(isChecked) {
        $('input[name="permission[]"]').each(function() {
            this.checked = true;
        });
    } else {
        $('input[name="permission[]"]').each(function() {
            this.checked = false;
        });
    }
}
</script>

#############################Role edit.blade.php################################
@extends('layouts.frontend')
@section('content')
<div class="content-wrapper">
  <!-- Content Header (Page header) -->
  <section class="content-header">
    <div class="container-fluid">
      <div class="row mb-2">
        <div class="col-sm-6">
          <h1>Roles</h1>
        </div>
        <div class="col-sm-6">
          <ol class="breadcrumb float-sm-right">
            <li class="breadcrumb-item"><a href="{{url('home')}}">Home</a></li>
            <li class="breadcrumb-item"><a href="{{url('permissions')}}">Role</a>
            <li class="breadcrumb-item active">Roles Edit</li>
          </ol>
        </div>
      </div>
    </div>
    <!-- /.container-fluid -->
  </section>
  <!-- Main content -->
  <section class="content">
    <div class="container-fluid">
      <form method="POST" action="{{route('roles.update')}}" enctype="multipart/form-data">
        @csrf
        <div class="row">
          <!-- / Form open here -->
          <div class="col-6">
            <!-- Default box -->
            <div class="card">
              <div class="card-header">
                <h3 class="card-title">Role Edit</h3>
                <div class="card-tools">
                  <button type="button" class="btn btn-tool" data-card-widget="collapse" data-toggle="tooltip" title="Collapse"> <i class="fas fa-minus"></i></button>
                  <button type="button" class="btn btn-tool" data-card-widget="remove" data-toggle="tooltip" title="Remove"> <i class="fas fa-times"></i></button>
                </div>
              </div>
              <div class="card-body"> @foreach($roles as $key =>  $role)
                <div class="form-group">
                  <label class="required" for="title">Role Name</label>
                  <input class="form-control {{ $errors->has('name') ? 'is-invalid' : '' }}" type="text" name="name" id="name" value="{{$role->name}}" >
                  @if($errors->has('name')) <span class="text-danger">{{ $errors->first('name') }}</span> @endif </div>
                <div class="form-group">
                  <label class="required" for="title">Permission Name</label>
                  <div> @foreach ($rolehpermissions as $key => $value) <span class = "badge badge-secondary">{{ $value }}</span> @endforeach </div>
                </div>
                @endforeach </div>
              <!-- /.card-body -->
            </div>
            <!-- /.card -->
          </div>
          <div class="col-6">
            <!-- Default box -->
            <div class="card">
              <div class="card-header">
                <h3 class="card-title">Permissions List</h3>
                <div class="card-tools">
                  <button type="button" class="btn btn-tool" data-card-widget="collapse" data-toggle="tooltip" title="Collapse"> <i class="fas fa-minus"></i></button>
                  <button type="button" class="btn btn-tool" data-card-widget="remove" data-toggle="tooltip" title="Remove"> <i class="fas fa-times"></i></button>
                </div>
              </div>
              <div class="card-body">
                <?php $cnt = count($permissions); if ($cnt>0) {?>
                <label class="required" for="title">Update Permissions</label>
                <div id="divCheckAll">
                  <input type="checkbox" name="checkall" id="checkall" onClick="check_uncheck_checkbox(this.checked);" />
                  Select / Deselect All </div>
                <div class="form-group"> @foreach($permissions as $key =>  $permission)
                  <input type="checkbox" value="{{ $permission->id }}" name="permission[]"  />
                  &nbsp;{{ $permission->name}}                                       
                  @endforeach
                  <?php } else { ?>
                  <p>Record not found.</p>
                  <?php } ?>
                </div>
                <div class="form-group">
                  <input type="hidden" name="id" id="id" value="{{$role->id}}" >
                  <button class="btn btn-success" type="submit"> Save </button>
                  <input class="btn btn-danger" action="action" onclick="window.history.go(-1); return false;" type="submit" value="Cancel"/>
                </div>
              </div>
              <!-- /.card-body -->
            </div>
            <!-- /.card -->
          </div>
          <!-- / Form close here -->
        </div>
      </form>
    </div>
  </section>
  <!-- /.content -->
</div>
@endsection
<script>
function check_uncheck_checkbox(isChecked) {
    if(isChecked) {
        $('input[name="permission[]"]').each(function() {
            this.checked = true;
        });
    } else {
        $('input[name="permission[]"]').each(function() {
            this.checked = false;
        });
    }
}
</script>

#############################Role show.blade.php###############################
@extends('layouts.frontend')
@section('content')
<div class="content-wrapper">
  <!-- Content Header (Page header) -->
  <section class="content-header">
    <div class="container-fluid">
      <div class="row mb-2">
        <div class="col-sm-6">
          <h1>Permissions</h1>
        </div>
        <div class="col-sm-6">
          <ol class="breadcrumb float-sm-right">
            <li class="breadcrumb-item"><a href="{{url('home')}}">Home</a></li>
            <li class="breadcrumb-item"><a href="{{url('permissions')}}">Permissions</a>
            <li class="breadcrumb-item active">Permissions Show</li>
          </ol>
        </div>
      </div>
    </div>
    <!-- /.container-fluid -->
  </section>
  <!-- Main content -->
  <section class="content">
    <div class="container-fluid">
      <div class="row">
        <div class="col-12">
          <!-- Default box -->
          <div class="card">
            <div class="card-header">
              <h3 class="card-title">Permissions Show</h3>
              <div class="card-tools">
                <button type="button" class="btn btn-tool" data-card-widget="collapse" data-toggle="tooltip" title="Collapse"> <i class="fas fa-minus"></i></button>
                <button type="button" class="btn btn-tool" data-card-widget="remove" data-toggle="tooltip" title="Remove"> <i class="fas fa-times"></i></button>
              </div>
            </div>
            <div class="card-body">
              <table class="table table-bordered data-table">
                <thead>
                  <tr>
                    <th width="150px"><strong>Id</strong></th>
                    <td> {{ $role->id }}</td>
                  </tr>
                  <tr>
                    <th width="150px"><strong>Name</strong></th>
                    <td> {{ $role->name }}</td>
                  </tr>
                  <tr>
                    <th width="150px"><strong>Permissions</strong></th>
                    <td>@if(!empty($rolePermissions))
                      @foreach($rolePermissions as $v) <span class = "badge badge-secondary">{{ $v->name }}</span> @endforeach
                      @endif </td>
                  </tr>
                  <tr>
                    <th colspan="2" align="center"><input class="btn btn-danger" action="action" onclick="window.history.go(-1); return false;" type="submit" value="Back"/></th>
                </thead>
              </table>
            </div>
            <!-- /.card-body -->
          </div>
          <!-- /.card -->
        </div>
      </div>
    </div>
  </section>
  <!-- /.content -->
</div>
@endsection

#############################User index.blade.php###############################

@extends('layouts.frontend')
@section('css')
<style>
tfoot { display: table-header-group; } table.dataTable input:nth-child(1) { width:100%; }
</style>
<link rel="stylesheet" href="{{ asset('public/admin/plugins/datatables-bs4/css/dataTables.bootstrap4.min.css') }}">
<link rel="stylesheet" href="{{ asset('public/admin/plugins/datatables-responsive/css/responsive.bootstrap4.min.css') }}">
@endsection
@section('content')
<div class="content-wrapper">
  <!-- Content Header (Page header) -->
  <section class="content-header">
    <div class="container-fluid">
      <div class="row mb-2">
        <div class="col-sm-6">
          <h1>Users</h1>
        </div>
        <div class="col-sm-6">
          <ol class="breadcrumb float-sm-right">
            <li class="breadcrumb-item"><a href="{{url('home')}}">Home</a></li>
            <li class="breadcrumb-item active">Users</li>
          </ol>
        </div>
      </div>
    </div>
    <!-- /.container-fluid -->
  </section>
  <!-- Main content -->
  <section class="content">
    <div class="container-fluid">
      <div class="row">
        <div class="col-12">
          <!-- Default box -->
          <div class="card">
            <div class="card-header">
              <h3 class="card-title">Users Listing</h3>
              <div class="card-tools"> <a href="{{url('user/downloaduserpdf')}}">Download PDF</a> | <a href="{{url('user/downloaduserxls')}}">Download XLS</a>
                <button type="button" class="btn btn-tool" data-card-widget="collapse" data-toggle="tooltip" title="Collapse"> <i class="fas fa-minus"></i></button>
                <button type="button" class="btn btn-tool" data-card-widget="remove" data-toggle="tooltip" title="Remove"> <i class="fas fa-times"></i></button>
              </div>
            </div>
            <div class="card-body">
              <table class="table table-bordered yajra-datatable">
                <thead>
                  <tr>
                    <th>Id</th>
                    <th>Name</th>
                    <th>Email</th>
                    <th>Role</th>
                    <th>Status</th>
                    <th>Action</th>
                  </tr>
                </thead>
                <tfoot>
                  <tr>
                    <th>Id</th>
                    <th>Name</th>
                    <th>Email</th>
                    <th>Role</th>
                    <th hidden>Status</th>
                    <th hidden>Action</th>
                  </tr>
                </tfoot>
              </table>
            </div>
            <!-- /.card-body -->
          </div>
          <!-- /.card -->
        </div>
      </div>
    </div>
  </section>
  <!-- /.content -->
</div>
@endsection
@section('script')
<script type="text/javascript">
$(document).ready(function(){
var table = $('.yajra-datatable').DataTable({
        processing: true,
        serverSide: true,
        ajax: "{{ url('user') }}",
        columns: [            
            {data: 'id'},
            {data: 'name'},
            {data: 'email'},
            {data: 'roles'},                 
            {data: 'st',orderable: false},            
            {data: 'action', orderable: false, searchable: false}
        ],
                
        initComplete: function () {
        this.api().columns().every(function () {
            var column = this;
            var input = document.createElement("input");
            $(input).appendTo($(column.footer()).empty())
            .on('change', function () {
                column.search($(this).val(), false, false, true).draw();
            });
        });
    }    
 });
});
</script>
<script src="{{ asset('public/admin/plugins/datatables/jquery.dataTables.min.js') }}"></script>
<script src="{{ asset('public/admin/plugins/datatables-bs4/js/dataTables.bootstrap4.min.js') }}"></script>
<script src="{{ asset('public/admin/plugins/datatables-responsive/js/dataTables.responsive.min.js') }}"></script>
<script src="{{ asset('public/admin/plugins/datatables-responsive/js/responsive.bootstrap4.min.js') }}"></script>
@endsection

#############################User edit.blade.php#################################

Edit.blade.php

@extends('layouts.frontend')
@section('css')
@endsection
@section('content')
<div class="content-wrapper">
  <!-- Content Header (Page header) -->
  <section class="content-header">
    <div class="container-fluid">
      <div class="row mb-2">
        <div class="col-sm-6">
          <h1>Users</h1>
        </div>
        <div class="col-sm-6">
          <ol class="breadcrumb float-sm-right">
            <li class="breadcrumb-item"><a href="{{url('home')}}">Home</a></li>
            <li class="breadcrumb-item"><a href="{{url('user')}}">Users</a>
            <li class="breadcrumb-item active">User Show</li>
          </ol>
        </div>
      </div>
    </div>
    <!-- /.container-fluid -->
  </section>
  <!-- Main content -->
  <section class="content">
    <div class="container-fluid">
      <div class="row">
        <div class="col-6">
          <!-- Default box -->
          <div class="card">
            <div class="card-header">
              <h3 class="card-title">Users Show</h3>
              <div class="card-tools">
                <button type="button" class="btn btn-tool" data-card-widget="collapse" data-toggle="tooltip" title="Collapse"> <i class="fas fa-minus"></i></button>
                <button type="button" class="btn btn-tool" data-card-widget="remove" data-toggle="tooltip" title="Remove"> <i class="fas fa-times"></i></button>
              </div>
            </div>
            <div class="card-body">
              <form method="POST" action="{{route('user.update')}}" enctype="multipart/form-data">
                @csrf
                <?php $cnt = count($data_array); if ($cnt>0) {?>
                @foreach($data_array as $key =>  $data_array)
                <div class="row">
                  <div class="col-sm-12">
                    <div class="form-group">
                      <label class="required" for="title">User Name <span class="text-danger">*</span></label>
                      <input class="form-control {{ $errors->has('name') ? 'is-invalid' : '' }}" type="text" name="name" id="name"  value="{{$data_array->name}}" required>
                      @if($errors->has('name')) <span class="text-danger">{{ $errors->first('name') }}</span> @endif </div>
                    <div class="form-group">
                      <label class="required" for="title">Email <span class="text-danger">*</span></label>
                      <input class="form-control {{ $errors->has('email') ? 'is-invalid' : '' }}" type="text" name="email" id="email" value="{{$data_array->email}}" required>
                      @if($errors->has('email')) <span class="text-danger">{{ $errors->first('email') }}</span> @endif </div>
                    <div class="form-group">
                      <label class="required" for="title">Status <span class="text-danger">*</span></label>
                      <input type="radio" name="status" value="1" <?php  if($data_array->status == 1) { echo "checked "; }  ?> />
                      Active
                      <input type="radio" name="status" value="0" <?php  if($data_array->status == 0) { echo "checked "; }  ?>/>
                      Inactive   @if($errors->has('status')) <span class="text-danger">{{ $errors->first('status') }}</span> @endif </div>
                    <label class="required" for="title">Assigned Roles <span class="text-danger">*</span></label>
                    @foreach($assignedroles as $key =>  $assignedrole) <span class = "badge badge-secondary">{{ $assignedrole->name}} </span> @endforeach </div>
                </div>
                @endforeach
                <?php } else { ?>
                <p>Record not found.</p>
                <?php } ?>
                <div class="row">
                  <div class="col-md-6">
                    <div class="form-group">
                      <input type="hidden" name="id" id="id" value="{{$data_array->id}}" >
                      <button class="btn btn-success" type="submit"> Update </button>
                      <input class="btn btn-danger" action="action" onclick="window.history.go(-1); return false;" type="submit" value="Cancel"/>
                    </div>
                  </div>
                </div>
              </form>
            </div>
            <!-- /.card-body -->
          </div>
          <!-- /.card -->
        </div>
        <div class="col-6">
          <!-- Default box -->
          <div class="card">
            <div class="card-header">
              <h3 class="card-title">Users Roles</h3>
              <div class="card-tools">
                <button type="button" class="btn btn-tool" data-card-widget="collapse" data-toggle="tooltip" title="Collapse"> <i class="fas fa-minus"></i></button>
                <button type="button" class="btn btn-tool" data-card-widget="remove" data-toggle="tooltip" title="Remove"> <i class="fas fa-times"></i></button>
              </div>
            </div>
            <div class="card-body">
              <form method="POST" action="{{route('user.updateroles')}}" enctype="multipart/form-data">
                @csrf
                <div class="row">
                  <div class="col-sm-12">
                    <?php $cnt = count($roles); if ($cnt>0) {?>
                    <label class="required" for="title">Update Permissions</label>
                    <div id="divCheckAll">
                      <input type="checkbox" name="checkall" id="checkall" onClick="check_uncheck_checkbox(this.checked);" />
                      Select / Deselect All </div>
                    <div class="form-group"> @foreach($roles as $key =>  $role)
                      <input type="checkbox" value="{{ $role->id }}" name="role[]"  />
                      &nbsp;{{ $role->name}}                                       
                      @endforeach </div>
                    <?php } else { ?>
                    <p>Record not found.</p>
                    <?php } ?>
                  </div>
                </div>
                <div class="row">
                  <div class="col-md-6">
                    <div class="form-group">
                      <input type="hidden" name="id" id="id" value="{{$data_array->id}}" >
                      <button class="btn btn-success" type="submit"> Update </button>
                      <input class="btn btn-danger" action="action" onclick="window.history.go(-1); return false;" type="submit" value="Cancel"/>
                    </div>
                  </div>
                </div>
              </form>
            </div>
            <!-- /.card-body -->
          </div>
          <!-- /.card -->
        </div>
      </div>
    </div>
  </section>
  <!-- /.content -->
</div>
@endsection
@section('script')
<script>
function check_uncheck_checkbox(isChecked) {
    if(isChecked) {
        $('input[name="role[]"]').each(function() {
            this.checked = true;
        });
    } else {
        $('input[name="role[]"]').each(function() {
            this.checked = false;
        });
    }
}
</script>
@endsection

#############################User show.blade.php#################################

@extends('layouts.frontend')
@section('content')
<div class="content-wrapper">
  <!-- Content Header (Page header) -->
  <section class="content-header">
    <div class="container-fluid">
      <div class="row mb-2">
        <div class="col-sm-6">
          <h1>Users</h1>
        </div>
        <div class="col-sm-6">
          <ol class="breadcrumb float-sm-right">
            <li class="breadcrumb-item"><a href="{{url('home')}}">Home</a></li>
            <li class="breadcrumb-item"><a href="{{url('user')}}">Users</a>
            <li class="breadcrumb-item active">User Show</li>
          </ol>
        </div>
      </div>
    </div>
    <!-- /.container-fluid -->
  </section>
  <!-- Main content -->
  <section class="content">
    <div class="container-fluid">
      <div class="row">
        <div class="col-12">
          <!-- Default box -->
          <div class="card">
            <div class="card-header">
              <h3 class="card-title">Users Show</h3>
              <div class="card-tools">
                <button type="button" class="btn btn-tool" data-card-widget="collapse" data-toggle="tooltip" title="Collapse"> <i class="fas fa-minus"></i></button>
                <button type="button" class="btn btn-tool" data-card-widget="remove" data-toggle="tooltip" title="Remove"> <i class="fas fa-times"></i></button>
              </div>
            </div>
            <div class="card-body">
              <table class="table table-bordered data-table">
                <thead>
                  <?php $cnt = count($data_array); if ($cnt>0) {?>
                @foreach($data_array as $key =>  $data_array)
                <tr>
                  <th width="150px"><strong>Id</strong></th>
                  <th>{{$data_array->id}}</th>
                </tr>
                <tr>
                  <th width="150px"><strong>Name</strong></th>
                  <th>{{$data_array->name}}</th>
                </tr>
                <tr>
                  <th width="150px"><strong>Email</strong></th>
                  <th>{{$data_array->email}}</th>
                </tr>
                <tr>
                  <th width="150px"><strong>Status</strong></th>
                  <th>@if($data_array->status==0)Inactive
                    @else
                    Active
                    @endif</th>
                </tr>
                <tr>
                  <th width="150px"><strong>Roles</strong></th>
                  <th> @foreach($assignedroles as $key =>  $assignedrole) <span class = "badge badge-secondary">{{ $assignedrole->name}} </span> @endforeach</th>
                </tr>
                <tr> @endforeach
                  <?php } else { ?>
                <tr>
                  <td colspan="2"><p>Record not found.</p></td>
                </tr>
                <?php } ?>
                <th colspan="2" align="center"><input class="btn btn-danger" action="action" onclick="window.history.go(-1); return false;" type="submit" value="Back"/></th>
                  </thead>
              </table>
            </div>
            <!-- /.card-body -->
          </div>
          <!-- /.card -->
        </div>
      </div>
    </div>
  </section>
  <!-- /.content -->
</div>
@endsection 

#############################User downloaduserpdf.blade.php#######################

<table class="table table-bordered data-table">
  <thead>
    <tr>
      <th colspan="4"> Users Data</th>
    </tr>
    <tr>
      <th  width="50" bgcolor="#00FFCC">ID</th>
      <th  width="200" bgcolor="#00FFCC">Name</th>
      <th  width="200" bgcolor="#00FFCC">Email</th>
      <th  width="50" bgcolor="#00FFCC">Status</th>
    </tr>
  </thead>
  <tbody>  
  @foreach($data_arrays as $key => $data_array)
  <tr>
    <td align="center">{{ $data_array->id}}</td>
    <th align="left">{{ $data_array->name}}</th>
    <th align="left">{{ $data_array->email}}</th>
    <th align="center"><?php if($data_array->status==0) { ?>
      <span style='cursor:pointer;' id='{{$data_array->id}}/{{$data_array->status}}' class='status btn btn-danger btn-sm'>Inactive</span>
      <?php } else { ?>
      <span style='cursor:pointer;' id='{{$data_array->id}}/{{$data_array->status}}' class='status btn btn-primary btn-sm'>Active</span>
      <?php  }  ?>
    </th>
  </tr>
  @endforeach
  </tbody>  
</table>

Saturday, 22 August 2020

How to create laravel project in laravel 7 and 8 using xampp


Step 1: composer create-project --prefer-dist laravel/laravel project-name

Step 2: cd project-name
 
Step 3: composer require laravel/ui

Step 4: php artisan ui bootstrap --auth

Step 5: npm install && npm run development

Step 6: open the .en file write the database name, username and password as below.
DB_DATABASE=demo
DB_USERNAME=root
DB_PASSWORD=

Step 7: run [ php artisan migrate ]

Step Extra:  Factory and Seeders

Step 8: To to remove public from url.
Copy .htaccess from public folder and paste to root directory.
Rename server.php to index.php update below lines.

To set the css and js

open resources/views/layouts/app.blade.php
add public in ur of js and css
    <!-- Scripts -->
    <script src="{{ asset('public/js/app.js') }}" defer></script>
    <!-- Styles -->
    <link href="{{ asset('public/css/app.css') }}" rel="stylesheet">

Step 9: To change the length of password

Open app\Http\Controllers\AuthRegisterController and find below lines.   

protected function validator(array $data)
    {
        return Validator::make($data, [
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
            'password' => ['required', 'string', 'min:8', 'confirmed'],
        ]);
    }

Change min:8 to your your requirement.

Step 10: Error page. 

To show our own error page, create a folder named errors view folder. Create a file named 503.blade.php and write your error message.


Best methods and Laravel packages we should have in our project.

Step 11: Install laravel debugbar for debuging

github.com/barryvdh/laravel-debugbar
composer require barryvdh/laravel-debugbar --dev

To remove any package just remove lines from Composer.json and run command [  composer update ]

Step 12: DOMPDF helps us to convert HTML to PDF files. 

 Repository – github.com/barryvdh/laravel-dompdf
composer require barryvdh/laravel-dompdf
Add  ServiceProvider to the providers array in config/app.php
        Barryvdh\DomPDF\ServiceProvider::class,
Add this to your facades:
        'PDF' => Barryvdh\DomPDF\Facade::class,

php artisan vendor:publish --provider="Barryvdh\DomPDF\ServiceProvider"

In the controller file add use PDF and add a function like below

public function downloadpdf()
    {   
        $data_arrays = DB::table('city')->orderBy('id', 'desc')->get();           
         $pdf = PDF::loadView('downloadpdf',['data_arrays' => $data_arrays]);
        return $pdf->download('City.pdf');
    }
Also create a downloadpdf.blade.php file

Step 13: Laravel Excel

composer require maatwebsite/excel
php artisan vendor:publish --provider="Maatwebsite\Excel\ExcelServiceProvider"
Repository - github.com/Maatwebsite/Laravel-Excel

Step 14: SEO Tools

composer require artesaos/seotools
php artisan vendor:publish --provider="Artesaos\SEOTools\Providers\SEOToolsServiceProvider"
https://packalyst.com/packages/package/artesaos/seotools

example: In the app.blade.php put the below line for generating meta contents
{!! SEOMeta::generate() !!}
In the controller file add
        use SEOMeta;
In the function file add
        SEOMeta::setTitle('Search result');
        SEOMeta::setDescription('This is search result page');
        SEOMeta::addKeyword(['keyword1','keyword2','keyword3','keyword4']);

Step :15 No Captcha

composer require anhskohbo/no-captcha
php artisan vendor:publish --provider="Anhskohbo\NoCaptcha\NoCaptchaServiceProvider"
https://packalyst.com/packages/package/anhskohbo/no-captcha

Add below line in login.blade.php after password div.

<div class="row">
              <div class="col-md-4"></div>
              <div class="form-group col-md-4">
              <label for="ReCaptcha">Recaptcha:</label>
              {!! NoCaptcha::renderJs() !!}
              {!! NoCaptcha::display() !!}            
               @error('g-recaptcha-response')
                   <span class="invalid-feedback d-block justify-content-center" role="alert">
                   <strong>{{ $message }}</strong> </span>
               @enderror             
                           
                </div>
            </div>

In the login controller make a function named validateLogin as shown below.

use Illuminate\http\Request;
protected function validateLogin(Request $request)
    {   
         $this->validate($request,[
            'email' => ['required', 'string', 'email'],
            'password' => ['required', 'string'],
            'g-recaptcha-response' => ['required','captcha'],
        ]);
    }
In the env file add 2 new variables as shown below.

NOCAPTCHA_SECRET = xxxxxxxxxxxxxx
NOCAPTCHA_SITEKEY = xxxxxxxxxxxxx

Step 16: Socialite

composer require laravel/socialite

1. Create route
Route::get('/login/github',[App\Http\Controllers\Auth\LoginController::class,'redirectToGithub']);
Route::get('/login/github/callback',[App\Http\Controllers\Auth\LoginController::class,'handleGithubCallback']);

2. Add in .env file 0705
GITHUB_CLIENT_ID="04b9d17e708b7c887607"
GITHUB_CLIENT_SECRET="47c4a4e241e8130b1fdfc4cbaa16b011d7bf709e"

3. Add in config/services.php
'github' => [
        'client_id' => env('GITHUB_CLIENT_ID'),
        'client_secret' => env('GITHUB_CLIENT_SECRET'),
        'redirect' => env('http://localhost/practise/login/github/callback'),
    ],

4. Add code in login controller
    use Laravel\Socialite\Facades\Socialite;
    use Auth; use App\Models\User;

public function redirectToGithub()
    {
        return Socialite::driver('github')->redirect();
    }
    
    public function handleGithubCallback()
    {
        $user = Socialite::driver('github')->user();
        $this->registerOrLoginUser($user);
        return redirect('home');
    }
    
    protected function registerOrLoginUser($data)
    {
        $user = User::where('email','=', $data->email)->first();
        if(!$user){
            $user = new User();
            $user->name = $data->name;
            $user->email = $data->email;
            $user->provider_id = $data->id;             
            $user->save();
        }
        Auth::login($user);   
    }

5. Add this code in login file for sign in.
<div class="form-group row">
  <div class="col-md-8 offset-md-4">
    <a class="btn btn-primary" href="{{url('login/github')}}"> {{ __('Sign In with Github?') }} </a> </div>
</div>

6. Create a field in user table : varchar 100 : Null ] and update password field with Null.
php artisan cache:clear
composer dump-autoload


Step 17: Disable Registration | Enable Email Verification | Disable Reset Password

All you need to do is add a parameter in routes/web.php:
Auth::routes([
  'register' => false,
  'verify' => true,
  'reset' => false
]);

Step 18:  Email verification

For testing the mail register in https://mailtrap.io/ You will get the username and password
Open the .env file and set the value

    MAIL_MAILER=smtp
    MAIL_HOST=smtp.mailtrap.io
    MAIL_PORT=2525
    MAIL_USERNAME=xxxxxxx
    MAIL_PASSWORD=xxxxxxx
    MAIL_ENCRYPTION=null
    MAIL_FROM_ADDRESS=rameshyadavjee@gmail.com
    MAIL_FROM_NAME="${APP_NAME}"

*open app/User.php and update the class
    class User extends Authenticatable implements MustVerifyEmail
*open web.php and add Auth::routes(['verify' => true]);
* open HomeController.php and add this line in constructor
    public function __construct()
    {
        $this->middleware(['auth','verified']);
    }    


Step 19: Store IP Address of users login

 composer require yadahan/laravel-authentication-log
run  [ php artisan vendor:publish --provider="Yadahan\AuthenticationLog\AuthenticationLogServiceProvider" ]
run php artisan migrate
Open the users model and add below lines.
        use Yadahan\AuthenticationLog\AuthenticationLogable;

        class User extends Authenticatable
        {    
              use Notifiable, AuthenticationLogable;
          ......    

Step 20: GeoLocation
composer require torann/geoip
'providers' => [
      \Torann\GeoIP\GeoIPServiceProvider::class,
 ]
  'aliases' => [
      'GeoIP' => \Torann\GeoIP\Facades\GeoIP::class,
];
php artisan vendor:publish --provider="Torann\GeoIP\GeoIPServiceProvider" --tag=config
In the config/geoip.php update the 'cache_tags' => [],
php artisan geoip:update
In the controller file
    $geoipInfo = geoip()->getLocation($_SERVER['REMOTE_ADDR']);
    return View('home',['geoipInfo' => $geoipInfo]);
In the view file
        IP: {{$geoipInfo->ip}}
        Country: {{$geoipInfo->country}}

Step 21: For front-end validation use parsley

https://parsleyjs.org/doc/examples.html
<link href="{{ asset('public/css/parsley.css') }}" rel="stylesheet">
<script src="{{ asset('public/js/parsley.min.js') }}" defer></script>

<form  name="rentagreement" id="rentagreement" action="{{ route('rentagreement.save') }}" method="post" enctype="multipart/form-data" data-parsley-validate>

        <input value="{{ old('ag_landlord_mobile') }}" class="form-control" type="text" name="ag_landlord_mobile" id="ag_landlord_mobile" data-parsley-type="number" data-parsley-maxlength="10" data-parsley-maxlength="10" data-parsley-trigger="keyup" required/>
        <input value="{{ old('ag_tenant_name') }}" class="form-control" type="text" name="ag_tenant_name" id="ag_tenant_name" data-parsley-pattern="^[a-zA-Z ]+$" data-parsley-trigger="keyup" required/>

Step 22: Laravel Backup

composer require spatie/laravel-backup
php artisan vendor:publish --provider="Spatie\Backup\BackupServiceProvider"

In your config/database.php file, edit the mysql database config and add:


  'dump' => [
               'dump_binary_path' => 'C:/xampp/mysql/bin/', // only the path, so without `mysqldump` or `pg_dump`
               'use_single_transaction',
               'timeout' => 60 * 5, // 5 minute timeout
            ],

Create a folder in storage\app  site-backup.

 Open config/backup.php file,  'name' => env('APP_NAME', 'laravel-backup'), It will create a folder. The default folder is Laravel. If you want to change the folder name. You can change as shown below.
'name' => 'site-backup',//env('APP_NAME', 'laravel-backup'), 

php artisan backup:run

Step 23: Laravel Migration Generator

composer require --dev "kitloong/laravel-migrations-generator"

https://github.com/kitloong/laravel-migrations-generator
Add below line in app.php in serviceprovider.

 \KitLoong\MigrationsGenerator\MigrationsGeneratorServiceProvider::class,

Run php artisan migrate:generate to create migrations for all the tables, or you can specify the tables you wish to generate using php artisan migrate:generate table1,table2,table3,table4,table5. You can also ignore tables with --ignore="table3,table4,table5"

Step 24: Toastr Package

composer require yoeunes/toastr
config/app.php

'providers' => [ 
        Yoeunes\Toastr\ToastrServiceProvider::class,
];

Put these line in  view or layout file.
         @
toastr_css

Place below lines in footer part
        @jquery
        @toastr_js
        @toastr_render

Use the below lines for toastr.

toastr()->success('Success Message');
toastr()->error('Error Message');
toastr()->info('Info Message');
toastr()->warning('Warning Message');

Step 25. Roles and Permission

Step 26. Multi Authentication

Step 27. Localization 

Step 28. Sending Email

Steps 29. composer require jdavidbakr/laravel-cache-garbage-collector

Then add the service provider to app/Console/Kernel.php in the $commands array:

\jdavidbakr\LaravelCacheGarbageCollector\LaravelCacheGarbageCollector::class

We will run this command :

php artisan cache:gc

Machine Learning - Potato Leaf Disease Prediction

Step 1: import numpy as np import pandas as pd import splitfolders import matplotlib.pyplot as plt import tensorflow as tf from tensorflow i...