Saturday, 22 August 2020

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


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

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

Step 4: php artisan ui bootstrap --auth

Step 5: npm install && npm run development

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

Step 7: run [ php artisan migrate ]

Step Extra:  Factory and Seeders

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

To set the css and js

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

Step 9: To change the length of password

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

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

Change min:8 to your your requirement.

Step 10: Error page. 

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


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

Step 11: Install laravel debugbar for debuging

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

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

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

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

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

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

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

Step 13: Laravel Excel

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

Step 14: SEO Tools

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

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

Step :15 No Captcha

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

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

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

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

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

NOCAPTCHA_SECRET = xxxxxxxxxxxxxx
NOCAPTCHA_SITEKEY = xxxxxxxxxxxxx

Step 16: Socialite

composer require laravel/socialite

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

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

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

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

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

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

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


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

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

Step 18:  Email verification

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

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

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


Step 19: Store IP Address of users login

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

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

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

Step 21: For front-end validation use parsley

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

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

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

Step 22: Laravel Backup

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

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


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

Create a folder in storage\app  site-backup.

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

php artisan backup:run

Step 23: Laravel Migration Generator

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

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

 \KitLoong\MigrationsGenerator\MigrationsGeneratorServiceProvider::class,

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

Step 24: Toastr Package

composer require yoeunes/toastr
config/app.php

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

Put these line in  view or layout file.
         @
toastr_css

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

Use the below lines for toastr.

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

Step 25. Roles and Permission

Step 26. Multi Authentication

Step 27. Localization 

Step 28. Sending Email

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

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

\jdavidbakr\LaravelCacheGarbageCollector\LaravelCacheGarbageCollector::class

We will run this command :

php artisan cache:gc

Machine Learning - Potato Leaf Disease Prediction

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