Monday, 8 October 2018

List of online users

Follow these Steps

1. In route file.

Route::get('/useronline', 'HomeController@useronline')->name('useronline');

2. In HomeController

<?php

namespace App\Http\Controllers;
use App\user;
use Illuminate\Http\Request;

class HomeController extends Controller
{
   public function __construct(){ $this->middleware('auth'); }
      
    public function useronline()
    {
        $users = User::all();
        return view('useronline',compact('users'));
    }

public function isOnline()
    {
        return Cache::has('user-is-online-'. $this->id);
    }
}

3. View: useronline.blade.php

@extends('layouts.app')

@section('content')
<div class="container">
  <div class="row justify-content-center">
    <div class="col-md-8">
      <div class="card">
        <div class="card-header">Online users</div>
        <div class="card-body">
          <table class="table">
            <thead>
              <tr>
                <th>Name</th>
                <th>Email</th>
                <th>Status</th>
              </tr>
            </thead>
            <tbody>
           
            @foreach ($users as $user)
            <tr>
              <td>{{ $user->name }}</td>
              <td>{{ $user->email }}</td>
              <td> @if ($user->isOnline())
                <li class="text-success"> Online </li>
                @else
                <li class="text-muted"> Offline </li>
                @endif </td>
            </tr>
            @endforeach
            </tbody>
           
          </table>
        </div>
      </div>
    </div>
  </div>
</div>
@endsection

How to login with username, email and mobile no?


checkstatus is a helper
<?php
namespace App\Http\Middleware;

use Closure;
use Auth;
use Session;

class CheckStatus
{
    public function handle($request, Closure $next)
    {
        $response = $next($request);
        if(Auth::check() && Auth::user()->status != '1'){
            Auth::logout();
            $request->session()->flash('alert-danger', 'Your Account is deactivated.');
            return redirect('/login')->with('erro_login', 'Your error text');
        }
        return $response;
    }
}
**********************************************************************************
Add below lines in login controller.

<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Session;
use App\User;

class LoginController extends Controller
{ 

use AuthenticatesUsers;
protected $redirectTo = RouteServiceProvider::HOME;


public function __construct()
    {
         $this->middleware(['guest','checkstatus'])->except('logout');
    }
   
public function login(Request $request)
   {     
         $email = $request->email;
         if(is_numeric($email))
         {
            $auth = Auth::guard('web')->attempt(['mobile'=>$email,'password'=>$request->password]);
         }
         elseif (filter_var($email, FILTER_VALIDATE_EMAIL))
         {
            $auth = Auth::guard('web')->attempt(['email'=>$email,'password'=>$request->password]);
          }
         else
         {
               $auth = Auth::guard('web')->attempt(['name'=>$email,'password'=>$request->password]);
          }

         if($auth)
         { 
           return redirect()->route('home');         
                  $request->session()->put('email', $email);
          } else {
              session()->flash('login', 'Either Email or Password is incorrect.');
              return redirect()->route('login');
          }

      }

public function getLogin()
    {
          if(Auth::guard('web')->check()) {       
           return redirect()->route('login');
          }
          return view('auth.login');
    }
}

Note: active field should be there in user table with int(1). 
 
Login form

<div class="flash-message">
@if(Session::has('login'))
<p class="alert alert-danger" role="alert">{{ Session::get('login') }} <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a></p>
@endif
</div>           

<div class="flash-message">
@foreach (['danger', 'warning', 'success', 'info'] as $msg)
@if(Session::has('alert-' . $msg))
<p class="alert alert-{{ $msg }}">{{ Session::get('alert-' . $msg) }} <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a></p>
@endif
@endforeach
</div>

<form method="POST" action="{{ route('login') }}">
@csrf
<div class="form-group row">
  <label for="email" class="col-md-4 col-form-label text-md-right">{{ __('Name/Mobile/E-Mail') }}</label>
  <div class="col-md-6">
    <input id="email" type="text" class="form-control @error('email') is-invalid @enderror" name="email" value="{{ old('email') }}" required autocomplete="email" autofocus>
    @error('email') <span class="invalid-feedback" role="alert"> <strong>{{ $message }}</strong> </span> @enderror </div>
</div>
<div class="form-group row">
  <label for="password" class="col-md-4 col-form-label text-md-right">{{ __('Password') }}</label>
  <div class="col-md-6">
    <input id="password" type="password" class="form-control @error('password') is-invalid @enderror" name="password" required autocomplete="current-password">
    @error('password') <span class="invalid-feedback" role="alert"> <strong>{{ $message }}</strong> </span> @enderror </div>
</div>
<div class="form-group row">
  <div class="col-md-6 offset-md-4">
    <div class="form-check">
      <input class="form-check-input" type="checkbox" name="remember" id="remember" {{ old('remember') ? 'checked' : '' }}>
      <label class="form-check-label" for="remember"> {{ __('Remember Me') }} </label>
    </div>
  </div>
</div>

<div class="form-group row mb-0">
  <div class="col-md-8 offset-md-4">
    <button type="submit" class="btn btn-primary"> {{ __('Login') }} </button>
    @if (Route::has('password.request')) <a class="btn btn-link" href="{{ route('password.request') }}"> {{ __('Forgot Your Password?') }} </a> @endif </div>
</div>
</form>

Prevent back history.

Create a middleware named PreventBackHistory

and add the below lines.

<?php
namespace App\Http\Middleware;

use Closure;

class PreventBackHistory
{
    public function handle($request, Closure $next)
    {
        $response = $next($request);

        return $response->header('Cache-Control','nocache, no-store, max-age=0, must-revalidate')

            ->header('Pragma','no-cache')

            ->header('Expires','Sun, 02 Jan 1990 00:00:00 GMT');
    }
}


Now Open the kernal.php.
Find  protected $routeMiddleware and add below line.

'prevent-back-history' => \App\Http\Middleware\PreventBackHistory::class,

In your route.php file write these lines.

Route::group(['middleware' => 'prevent-back-history'],function()
{

*********** Write your route files here. example************
           Route::get('/home', 'HomeController@index')->name('home');

});


Logout from Other device.

<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Session;
use App\User;
***************************************************
 
Add a field name session_id with varchar(100).

To logout from other device add below lines in login controller.

protected function sendLoginResponse(Request $request)
    {
         $request->session()->regenerate();
        $previous_session = Auth::User()->session_id;
        if ($previous_session) {
            Session::getHandler()->destroy($previous_session);
        }
   
        Auth::user()->session_id = Session::getId();
        Auth::user()->save();
        $this->clearLoginAttempts($request);
   
        return $this->authenticated($request, $this->guard()->user())
            ?: redirect()->intended($this->redirectPath());
    }

How to check status of user before login?

Create a middlewear named CheckStatus

and add the below lines.

<?php
namespace App\Http\Middleware;

use Closure;
use Auth;
use Session;

class CheckStatus
{
    public function handle($request, Closure $next)
    {
        $response = $next($request);
        if(Auth::check() && Auth::user()->status != '1'){
            Auth::logout();
            $request->session()->flash('alert-danger', 'Your Account is deactivated.');
            return redirect('/login')->with('erro_login', 'Your error text');
        }
        return $response;
    }
}

Now Open the kernal.php.
Find  protected $routeMiddleware and add below line.

'checkstatus' => \App\Http\Middleware\CheckStatus::class,

Next: In loginController contructor should be updated as below.

public function __construct()  { $this->middleware(['guest','checkstatus'])->except('logout');  }

Next: In  your login.blade.php the error should be there.


<div class="flash-message"> @foreach (['danger', 'warning', 'success', 'info'] as $msg)
            @if(Session::has('alert-' . $msg))
            <p class="alert alert-{{ $msg }}">{{ Session::get('alert-' . $msg) }} <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a></p>
            @endif
            @endforeach </div>

Note. In your user table status field with int(1) should be there.

Monday, 2 July 2018

How to export data in csv / xls/ xlsx?

Step1:

Execute this command "composer require maatwebsite/excel"

Add Service Provider and Facade on config/app.php.
      Maatwebsite\Excel\ExcelServiceProvider::class,

     'Excel' => Maatwebsite\Excel\Facades\Excel::class,

execute this command :
php artisan vendor:publish --provider=Maatwebsite\Excel\ExcelServiceProvider

Step2:
Create a controller for DataTables application using Artisan.
php artisan make:controller DatatablesController
namespace App\Http\Controllers;
use App\Http\Requests;
use App\User;
use Yajra\Datatables\Datatables;

class DatatablesController extends Controller
{
    public function getIndex()
    {
        return view('datatables.index');
    }  

    public function anyData()
    {
        return Datatables::of(User::query())->make(true);
    }
}


Step:3
Register export routes in app\Htpp\routes.php
Route::get('datatables/{type}', 'DatatablesController@export_users');


***********************************************************
Step:4

Create a view file and add the below code.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Laravel DataTables Tutorial</title>
<!-- Bootstrap CSS -->
<link href="//netdna.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="//cdn.datatables.net/1.10.7/css/jquery.dataTables.min.css">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
            <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
            <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
        <![endif]-->
<style>
body {
    padding-top: 40px;
}
</style>
<!-- jQuery -->
<script src="//code.jquery.com/jquery.js"></script>
<!-- DataTables -->
<script src="//cdn.datatables.net/1.10.7/js/jquery.dataTables.min.js"></script>
<!-- Bootstrap JavaScript -->
<script src="//netdna.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<!-- App scripts -->
</head>
<body>
<div class="container">
  <div class="pull-right"> <a class="btn btn-primary" href="{{ url('users/csv') }}">Export to Csv </a> </div>
  <table class="table table-bordered" id="users-table">
    <thead>
      <tr>
        <th>Id</th>
        <th>Name</th>
        <th>Email</th>
        <th>Created At</th>
        <th>Updated At</th>
      </tr>
    </thead>
  </table>
</div>
<script>
$(function() {
    $('#users-table').DataTable({
        processing: true,
        serverSide: true,
        ajax: "{!! route('datatables.data') !!}",
        columns: [
            { data: 'id', name: 'id' },
            { data: 'name', name: 'name' },
            { data: 'email', name: 'email' },
            { data: 'created_at', name: 'created_at' },
            { data: 'updated_at', name: 'updated_at' }
        ]
    });
});
</script>
</body>
</html>

Sunday, 10 December 2017

How to remove public from url.


Copy .htaccess from public folder and paste to root directory.

Rename server.php to index.php update below lines.

How to remove error when first time php artisan migrate is done.


Step1: composer create-project --prefer-dist laravel/laravel project-name

Step2: cd project-name

Step3: composer require laravel/ui

Step4: php artisan ui bootstrap --auth

Step5: npm install && npm run development

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

Step7: Add below line in app/Providers/AppServiceProvider.php

use Illuminate\Support\Facades\Schema;
and replace boot() with below lines

 public function boot()
    {
        Schema::defaultStringlength(100);
    }

*******************************************************
open below files from /database/migrations
create_users_table.php and create_password_resets_table.php

If you want to change the default email length change and update as below.

The migration of password_resets's up() method would look like this:

Schema::create('password_resets', function (Blueprint $table) {
    $table->string('email');
    $table->string('token');
    $table->timestamp('created_at')->nullable();

    $table->unique([DB::raw('email(50)')]);
});

And for the migration of users:

Schema::create('users', function (Blueprint $table) {
    $table->increments('id');
    $table->string('name');
    $table->string('email');
    $table->string('password');
    $table->rememberToken();
    $table->timestamps();

    $table->index([DB::raw('email(50)')]);
});

Step7: run php artisan migrate

Step8: To to remove public from url.

Friday, 8 September 2017

2 ways to logout in laravel

There are 2 ways to logout from laravel.


1st way
Routing.
    Route::get('/logout', 'Auth\LoginController@logout');

 Blade file.
     <?php if(Auth::check()){ ?>
    <a href="{{ url('/logout') }}">Logout</a>
    <?php } ?>

2nd way
Routing.
      Route::post('logout','auth\LoginController@getLogout');

Controller.
     public function getLogout()
    {
        $this->auth->logout();
        return redirect('/login');
    }


Blade file.
 <?php if(Auth::check()){ ?>
<a href="{{ url('/logout') }}" class="btn-primary" style="padding:10px;" onclick="event.preventDefault();document.getElementById('logout-form').submit();"> Logout </a>
<form id="logout-form" action="{{ url('/logout') }}" method="POST" style="display: none;">
{{ csrf_field() }}</form>

   <?php } ?>

Sunday, 9 July 2017

How to create yajra datatable?

Step1:
Execute this command "composer require yajra/laravel-datatables-oracle"
Add Datatables Service Provider and Facade on config/app.php.

        Yajra\Datatables\DatatablesServiceProvider::class,

       'Datatables' => Yajra\Datatables\Facades\Datatables::class,

Step2:
Create a controller for DataTables application using Artisan.
php artisan make:controller DatatablesController

namespace App\Http\Controllers;

use App\Http\Requests;
use App\User;
use Yajra\Datatables\Datatables;

class DatatablesController extends Controller
{
    public function getIndex()
    {
        return view('datatables.index');
    }
   
    public function anyData()
    {
        return Datatables::of(User::query())->make(true);
    }
}

Step:3
Register datatables routes in app\Htpp\routes.php

Route::get('/datatables', ['uses'=>'DatatablesController@getIndex']);
Route::get('/datatables/datatable', ['as'=>'datatables.data','uses'=>'DatatablesController@anyData']);

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

Step:4
Create a view file and add the below code.
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Laravel DataTables Tutorial</title>

        <!-- Bootstrap CSS -->
        <link href="//netdna.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet">
        <link rel="stylesheet" href="//cdn.datatables.net/1.10.7/css/jquery.dataTables.min.css">

        <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
        <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
        <!--[if lt IE 9]>
            <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
            <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
        <![endif]-->
        <style>
            body {
                padding-top: 40px;
            }
        </style>
    </head>
    <body>
        <div class="container">
           <table class="table table-bordered" id="users-table">
        <thead>
            <tr>
                <th>Id</th>
                <th>Name</th>
                <th>Email</th>
                <th>Created At</th>
                <th>Updated At</th>
            </tr>
        </thead>
    </table>
        </div>

<script>
$(function() {
    $('#users-table').DataTable({
        processing: true,
        serverSide: true,
        ajax: '{!! route('datatables.data') !!}',
        columns: [
            { data: 'id', name: 'id' },
            { data: 'name', name: 'name' },
            { data: 'email', name: 'email' },
            { data: 'created_at', name: 'created_at' },
            { data: 'updated_at', name: 'updated_at' }
        ]
    });
});
</script>
        <!-- jQuery -->
        <script src="//code.jquery.com/jquery.js"></script>
        <!-- DataTables -->
        <script src="//cdn.datatables.net/1.10.7/js/jquery.dataTables.min.js"></script>
        <!-- Bootstrap JavaScript -->
        <script src="//netdna.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
        <!-- App scripts -->
        @stack('scripts')
    </body>
</html>

How to create virtual host for in xampp

Step1:
In your C:\xampp\apache\conf\extra. Open httpd-vhosts.conf and below lines.

<VirtualHost jayesh.shah:80> 
    DocumentRoot "D:/xampp/htdocs/jayesh/public"
    ServerName jayesh.shah
ServerAlias www.jayesh.shah
<Directory "D:/xampp/htdocs/jayesh/public">
Options +FollowSymLinks
AllowOverride All
Require all granted
</Directory>
</VirtualHost>

Step2:
In your C:\Windows\System32\drivers\etc\
Open hosts file and add below line
                  192.168.10.106 jayesh.shah
                  192.168.10.106 www.jayesh.shah

Step3: Restart apache

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