Sunday, 27 December 2020

419 Session Expired

How to remove 419 Session Expired error.

Step 1. In .env file SESSION_DRIVER=file. Replace file with database.

Example: SESSION_DRIVER=database.

Step 2. In the config/session.php

 'driver' => env('SESSION_DRIVER', 'file'), Replace file with database

Example: 'driver' => env('SESSION_DRIVER', 'database'),

Step 3. Create a database name session.

php artisan session:table

php artisan migrate.


Friday, 25 December 2020

How to create shortcode in laravel

1. Create a middleware name PostShortCodeMiddleware

2. Add this middleware in the kernal file.

3. Create a shortcode.php and shorcodeurl.php in view folder.

4. Place the shortcode in any view file. I have placed it in home.blade.php
 {user_list}
{user_email}

<?php
namespace App\Http\Middleware;

use Closure;
use App\Post;
use DB;
use Illuminate\Http\Response;
class PostShortCodeMiddleware
{   
    public function handle($request, Closure $next)
    {
        $response = $next($request);
        if(!method_exists($response, 'content')):
            return $response;
        endif;
           
    if(method_exists($response, 'content')){       
        $posts =  DB::table('users')->select()->get();       
        $postslug =  DB::table('users')->select('email')->get();       
        $content = str_replace(array('{user_list}', '{user_email}'), array(view('posts.shortcode',['posts' => $posts]),  view('posts.shortcodeurl',['posts' => $postslug])), $response->content());
        $response->setContent($content);
        return $response;
    }       
  }
}

Add in the Middleware
protected $middleware = [
.......
        \App\Http\Middleware\PostShortCodeMiddleware::class,       
......       
          ];

shortcode.php

<table class="table table-bordered data-table">
  <thead>
    <tr>
      <th width="50px">ID</th>
      <th>Name</th>
      <th>Email</th>     
      <th>Created</th>
      <th>Updated</th>            
    </tr>
  </thead>
  <tbody>  
  <?php foreach ($posts as $post)  {?>
  <tr>
    <td><?php echo $post->id; ?></td>
    <td><?php echo $post->name; ?></td>
    <td><?php echo $post->email; ?></td>
    <td><?php echo $post->created_at; ?></td>        
    <td><?php echo $post->updated_at; ?></td>        
  </tr>
  <?php } ?>
  </tbody>  
</table>

shortcodeurl.php

<table class="table table-bordered data-table">
  <thead>
    <tr>
      <th>User Email</th>
    </tr>
  </thead>
  <tbody>  
  <?php foreach ($posts as $post)  {?>
  <tr>
    <td><?php echo $post->email; ?></td>    
  </tr>
  <?php } ?>
  </tbody>  
</table>

Friday, 18 December 2020

Important points to remember

 Use stack for including css and js file..

<head>
    <!-- Head Contents -->
   @stack('css')
    @stack('js')
</head>

In your template file
@push('css')
    <link rel="stylesheet" href="/build/assets/css/laravel.css">
@endpush

@push('css')
    <style> .....</style>
@endpush


@push('js')
    <script src="/example.js"></script>
@endpush

******************** **************************************************

Option for  isset

{{ isset($data) ? $data  : "Not available" }}

{{ $data or "Not available" }}

***********************************************************************

To include a Blade view from within another view. All variables that are available to the parent view will be made available to the included view:

<div>
    @include('shared.errors')
    <form>
        <!-- Form Contents -->
    </form>
</div>

and may also pass an array of extra data to the included view:

@include('view.name', ['some' => 'data'])

*************************************************************************

In env file you can make  production / local / staging

if (App::environment('local', 'staging')) {
    // The environment is either local OR staging...
}

'debug' => env('APP_DEBUG', false),
*************************************************************************
To reduce the length of password in registration. Open the RegisterController and set the new
length.
 
'password' => ['required', 'string', 'min:4', 'confirmed'],
 
*************************************************************************
How To Bypass CSRF Token For A Route In Laravel?
 
Path:- /app/Http/Middleware/VerifyCsrfToken.php

Add Below Code In The Class:-
protected $except = [
         'api/*', //For All Route starting with api.
         'your_url_here/', //For Specific url.
    ];

*************************************************************************

Stopping On First Validation Failure

Sometimes you may wish to stop running validation rules on an attribute after the first validation failure. To do so, assign the bail rule to the attribute:

$request->validate([
    'title' => 'bail|required|unique:posts|max:255',
    'body' => 'required',
]);

*************************************************************************

 If you do not want the validator to consider null values as invalid. For example:


$request->validate([
    'title' => 'required|unique:posts|max:255',
    'body' => 'required',
    'publish_at' => 'nullable|date',
]);

*************************************************************************
Reverse routing
From the controller and action name, convert back to the url.

In the web.php
Route::get('/mypage', 'HomeController@test');
you can change any name in route. You don't have to change in the blade file. The function
remains the same.

<a href="{{action('HomeController@test')}}"> Test Page</a>

HomeController
Class HomeController extends Controller {

function test() {
        return 'Hi, This is test page';
}

}
 *************************************************************************
Query Scope

I want  'active' Users from User table. Currently we are using where queries like this.
$activeUsers = User::where('status', 1)->get();

But we need same thing in any other module also. So we need write again and again this where queries. Now, we will use Scope Query. Create a scopeName function in model. Below is the user model.

public function scopeActive($query,$value)
{
    return $query->where('status', $value);
}

In different module or controller
Use App\user;

In function you can use like this.

$data_array = User::active(0)->get();
 
 *************************************************************************

Life cycle of Request

Cover image for Laravel Request Lifecycle
 

 

 

Tuesday, 8 December 2020

Factory and Seeder

Below is default factory.  Factories ->UserFactory..

<?php

use App\User;
use Faker\Generator as Faker;
use Illuminate\Support\Str;

$factory->define(User::class, function (Faker $faker) {
    return [
        'name' => $faker->name,
        'email' => $faker->unique()->safeEmail,
        'email_verified_at' => now(),
        'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password
        'remember_token' => Str::random(10),
    ];
});

Below is default Databaseseeders ->UserFactory..

<?php

use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{     
    public function run()
    {
       factory(App\User::class, 100)->create();
    }
}

Run

php artisan db:seed

Sunday, 6 December 2020

How to send email in Laravel 7 - 8

Step 1. Create mail
             php artisan make:mail Contact Mail

<?php
namespace App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;

class ContactMail extends Mailable
{
    use Queueable, SerializesModels;
    public $details;

    public function __construct($details
    {
       $this->details = $details;    
    }

  
  public function build()    
    {
        return $this->view('email');    
    }

Step 2: In the controller file, get the details of the fiels.   
use Illuminate\Support\Facades\Mail;

            $name = $request->input('name');
            $contact_email = $request->input('contact_email');   
            $subject = $request->input('subject');   
            $message = $request->input('message');               
            $receiver = 'rameshyadavjee@gmail.com';
           
            $details = [       
                'name' =>  $name,       
                'contact_email'=> $contact_email,
                'subject' => $subject,
                'message' => $message,
                'receiver' => $receiver
            ];
           
            Mail::to($receiver)->send(new \App\Mail\ContactMail($details));      
        
  // To use below one  use App\Mail\NewRegistrationMail;
           //Mail::to($receiver)->send(new NewRegistrationMail($details));         
         

Step 3: Create Blade View
             resources/views/email.blade.php

<html>
<head>
<title>New Inquiry</title>
</head>
<body>
<strong>Subject</strong>&nbsp;:&nbsp;{{$_REQUEST['subject']}}<br>
<strong>Name</strong>&nbsp;&nbsp;&nbsp;&nbsp;:&nbsp;&nbsp;{{$_REQUEST['name']}}<br>
<strong>Email</strong>&nbsp;&nbsp;&nbsp;&nbsp;:&nbsp;{{$_REQUEST['contact_email']}}<br>
<strong>Message</strong>&nbsp;:&nbsp;{{$_REQUEST['message']}}
</html>

or

<strong>Subject</strong>&nbsp;:&nbsp;{{$details['subject']}}<br>
<strong>Name</strong>&nbsp;&nbsp;&nbsp;&nbsp;:&nbsp;&nbsp;{{$details['name']}}<br>
<strong>Email</strong>&nbsp;&nbsp;&nbsp;&nbsp;:&nbsp;{{$details['contact_email']}}<br>
<strong>Message</strong>&nbsp;:&nbsp;{{$details['message']}}


That's it

Laravel Telescope

1. composer require laravel/telescope

2. php artisan telescope:install

3. php artisan migrate

4. php artisan vendor:publish --tag=telescope-migrations  
 
5. Prevent the Telescope package from being auto-discovered by adding the following
to your composer.json file:

"extra": {
    "laravel": {
        "dont-discover": [
            "laravel/telescope"
        ]
    }
},

6. If you want to disable Telescope's data collection entirely using the
enabled configuration option:

'enabled' => env('TELESCOPE_ENABLED', true),

7. To run the telesecope use as seen here the url. http://localhost/practise/public/telescope

8. Very important point is open the layout.blade.php from ..\vendor\laravel\telescope\resources\views\layout.blade.php. At the bottom of the file update the code. Practise is my project name.

<script>
    window.Telescope = @json($telescopeScriptVariables);
    window.Telescope.path = 'practise/public/telescope';
</script>

Note: practise is the project name.

That's it.


Saturday, 5 December 2020

How to create localization in laravel without url changing?

 Step 1. Create a route as shown below.

Route::get('en', function() { session(['locale' => 'en']); return back(); });
Route::get('hi', function() { session(['locale' => 'hi']); return back(); });

Step 2. Create a middleware named SetLocale and write the code as below.
            php artisan make:middleware SetLocale

<?php

namespace App\Http\Middleware;
use App;
use Closure;
class SetLocale
{  
    protected $supported_languages = ['en', 'hi'];     
    public function handle($request, Closure $next)
    {
        if(!session()->has('locale')) {
            session(['locale' => $request->getPreferredLanguage($this->supported_languages)]);
        }
        app()->setLocale(session('locale'));
        return $next($request);
    }
}
 

Step 3. Add the SetLocale middleware in kernal.php

In the  protected $middlewareGroups = [
        'web' => [

                        \App\Http\Middleware\SetLocale::class, 

Step 4.Update the app.blade for navigation

<ul class="navbar-nav ml-auto">
          <!-- Authentication Links -->
          @guest
        ...
          @endif
          @else
      ...
          @endguest
         <li class="nav-item dropdown "> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Language </a>
            <div class="dropdown-menu" aria-labelledby="navbarDropdown">
            <a class="dropdown-item " href="{{url('en')}}">English</a>
            <div class="dropdown-divider"></div>
              <a class="dropdown-item" href="{{url('hi')}}">Hindi</a> </div>
          </li>

        </ul> 

It will look like this. 

Step 5. Create a folder name hi in resources\lang, now create a file named labels.php in hi folder through notepad and set the encoding =  UTF-8

<?php
return [   

'E-Mail Address' => 'ईमेल पता',
    'Reset Password' =>'पासवर्ड रीसेट',
    'Password' =>'पासवर्ड',
    'Login' => 'लॉग इन',
    'Remember Me' => 'मुझे याद रखें',
    'Reset Link' => 'पासवर्ड रीसेट लिंक भेजें',
    'Forgot you password' => 'आप पासवर्ड भूल गए',

]; 

Now to print the value {{  __('labels.Reset Password') }} or  {!!  __('labels.Reset Password') !!}

Thanks. 


 


Friday, 4 December 2020

Insert data using database seeder in laravel

Insert data using database seeder in laravel
php artisan make:seeder AdminsTableSeeder

<?php
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
class AdminsTableSeeder extends Seeder
{
    public function run()
    {
      DB::table('admins')->insert([
        'name'  => 'admin',
        'email' => 'admin@gmail.com',
        'password' => Hash::make('password'),
        ]);            
    }
}

composer dump-autoload

Run seeder
php artisan db:seed --class=AdminsTableSeeder

********************************************
To insert multiple record
public function run()
{
    DB::table('admins')->insert(array(
        array(
        'name' => "Steve",
        'email' => 'steve@gmail.com',
        'password' => Hash::make('secret'),
        ),
        array(
        'name' => "Laura",
        'email' => 'laura@gmail.com',
        'password' => Hash::make('secret'),
        )
    ));
}

********************************************
Insert data using factory in laravel
php artisan make:factory AdminsTableSeeder

<?php

use Faker\Generator as Faker;
use App\Models\Admin;
use Illuminate\Support\Str;
use Hash;

$factory->define(Admin::class, function (Faker $faker) {
    return [
        'name' => $faker->name,
        'email' =>$faker->email,        
        'password' => Hash::make('password'),
    ];
});

php artisan make:seeder AdminsTableSeeder
<?php
use Illuminate\Database\Seeder;

class AdminsTableSeeder extends Seeder
{   
    public function run()
    {        
        factory(App\Models\Admin::class, 100)->create();
    }
}
php artisan make:seeder AdminsTableSeeder

Thursday, 3 December 2020

Laravel Multi-authentication

php artisan make:migration create_admins_table --create=admins
Put this code in the Admin migration php file

public function up()
    {
        Schema::create('admins', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }

run  php artisan migrate

Add a record in admins table using seeder.

 Next: Create a model name Admin and copy paste below line.

php artisan make:model Models/Admins

<?php

namespace App;

use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Database\Eloquent\Model;

class Admin extends Model
{
    use Notifiable;
        protected $guard = 'admin';
        protected $fillable = ['name''email''password'];

        protected $hidden = [
            'password''remember_token',
        ];
}


Next In the config/auth.php file, set up the custom guards and providers for users and admins.
'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],
         'admin' => [
            'driver' => 'session',
            'provider' => 'admins',
        ],
        'api' => [
            'driver' => 'token',
            'provider' => 'users',
            'hash' => false,
        ],
    ],    
'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => App\Models\User::class,
        ],
        'admins' => [
            'driver' => 'eloquent',
            'model' => App\Models\Admin::class,
        ],        
    ],    

Next step is to create Admin controller
php artisan make:controller Admin\AdminController

class Admincontroller extends Controller {
    public function __construct()
    {
      $this->middleware('auth:admin');
    }
    public function index() {
        return View('admin.dashboard');
    }
}  

Next step is to create Admin Login Controller
php artisan make:controller Admin\AdminLoginController

<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Auth; use Route;

class AdminLoginController extends Controller
{
    public function __construct()
    {
      $this->middleware('guest:admin', ['except' => ['logout']]);
    }
    public function showLoginForm()
    {
        return View('admin.login');
    }
    
    public function login(Request $request)
    {
      // Validate the form data
      $this->validate($request, [
        'email'   => 'required|email',
        'password' => 'required|min:4'
      ]);
      
      // Attempt to log the user in
      if (Auth::guard('admin')->attempt(['email' => $request->email, 'password' => $request->password], $request->remember))             
      {
        // if successful, then redirect to their intended location
     
        return redirect('admin/dashboard');
      }
      // if unsuccessful, then redirect back to the login with the form data
      return redirect()->back()->withInput($request->only('email', 'remember'));
     }
    
    public function logout()
    {
        Auth::guard('admin')->logout();
        return redirect('/admin/login');
    }
}

Next Step is Create a new view file with the name admin.login.php for admin
Copy past from login form.
Make sure the <form method="POST" action="{{ route('admin.login') }}"> should be look like this.

Next Step is Create a new view file with the name dashboard.blade.php for admin

This is for laravel 7 . Now we will set our routes; routes/web.php.  

Route::prefix('admin')->group(function() {
    Route::get('/','Admin\AdminLoginController@showLoginForm')->name('admin.login');
    Route::get('/login','Admin\AdminLoginController@showLoginForm')->name('admin.login');
    Route::post('/login', 'Admin\AdminLoginController@login')->name('admin.login');
    Route::get('logout/', 'Admin\AdminLoginController@logout')->name('admin.logout');
    Route::get('/dashboard', 'Admin\AdminController@index')->name('admin.dashboard');
}) ;

This is for laravel 8 . Now we will set our routes; routes/web.php.

Route::get('/', function () { return view('welcome'); });
Auth::routes();
Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])->name('home');
Route::prefix('admin')->group(function () {
    Route::get('/',[App\Http\Controllers\Admin\AdminLoginController::class,'showLoginForm'])->name('admin.login');
    Route::get('login',[App\Http\Controllers\Admin\AdminLoginController::class,'showLoginForm'])->name('admin.login');
    Route::post('login',[App\Http\Controllers\Admin\AdminLoginController::class,'login'])->name('admin.login');
    Route::get('dashboard',[App\Http\Controllers\Admin\AdminController::class,'index'])->name('admin.index');
    Route::get('logout/', [App\Http\Controllers\Admin\AdminLoginController::class,'logout'])->name('admin.logout');
 });


Next step is, we have to set up the different login views for the guards. This in the app/Exceptions/Handler.php

use Illuminate\Support\Arr; use Auth;
protected function unauthenticated($request, AuthenticationException $exception)
{
        if ($request->expectsJson()) {
            return response()->json(['error' => 'Unauthenticated.'], 401);
        }
        
        $guard = Arr::get($exception->guards(), 0);
        switch ($guard){
            case 'admin':
                $login = 'admin.login';
                break;
            default:
                $login = 'login';
                break;
        }
        return redirect()->guest(route($login));
 }

Next step is If the login is successful, redirect to the dashboard of the specific guard. This is done in the RedirectIfAuthenticated.php    
public function handle($request, Closure $next, $guard = null)
    {
        switch ($guard) {
            case 'admin':
                if (Auth::guard($guard)->check()) {
                    return redirect()->route('admin.dashboard');
                }
                break;             
            default:
                if (Auth::guard($guard)->check()) {
                    return redirect('/home');
                }
                break;
        }
        return $next($request);
    }

That's it.

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>

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...