Thursday, 29 June 2023

Css Loader on ajax call

 <!DOCTYPE html>

<html>
<head>
  <title>AJAX Loader Example</title>
  <style>
    /* Styles for the loader */
    .loader-overlay {
      position: fixed;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background-color: rgba(0, 0, 0, 0.6);
      z-index: 9999;
      display: flex;
      justify-content: center;
      align-items: center;
      backdrop-filter: blur(5px); /* Apply the blur effect */
    }

    .loader {
      width: 40px;
      height: 40px;
      position: relative;
      animation: spin 1s infinite linear;
    }

    .loader:before,
    .loader:after {
      content: "";
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background-color: #3498db;
      transform: rotate(45deg);
      transform-origin: 50% 50%;
      border-radius: 50%;
      opacity: 0.8;
      animation: spinStar 1s infinite linear;
    }

    .loader:after {
      background-color: #f1c40f;
      opacity: 0.6;
      animation-delay: 0.5s;
    }

    @keyframes spin {
      0% {
        transform: rotate(0deg);
      }
      100% {
        transform: rotate(360deg);
      }
    }

    @keyframes spinStar {
      0% {
        transform: scale(1) rotate(45deg);
      }
      25% {
        transform: scale(0.6) rotate(45deg);
      }
      50% {
        transform: scale(1) rotate(45deg);
      }
      75% {
        transform: scale(1.4) rotate(45deg);
      }
      100% {
        transform: scale(1) rotate(45deg);
      }
    }

    /* Hide the loader by default */
    .hidden {
      display: none;
    }

    /* Adjust Bootstrap modal z-index */
    .modal {
      z-index: 1041 !important;
    }

    /* Adjust Bootstrap modal backdrop z-index */
    .modal-backdrop {
      z-index: 1040 !important;
    }
  </style>
</head>
<body>
  <!-- Loader overlay element -->
  <div id="loaderOverlay" class="loader-overlay hidden">
    <div class="loader"></div>
  </div>

  <!-- Page content -->
  <h1>Welcome to My Website</h1>
  <p>This is the content of the page.</p>

  <!-- Bootstrap modal -->
  <div class="modal fade" id="myModal">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title">Modal Title</h5>
          <button type="button" class="close" data-dismiss="modal">&times;</button>
        </div>
        <div class="modal-body">
          <p>This is the modal content.</p>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
          <button type="button" class="btn btn-primary">Save changes</button>
        </div>
      </div>
    </div>
  </div>

  <script>
    document.getElementById('loaderOverlay').classList.remove('hidden');

    makeAjaxRequest('https://example.com/api/data', function(response) {
      // Handle the response

      document.getElementById('loaderOverlay').classList.add('hidden');
    });

    function makeAjaxRequest(url, callback) {
      // Your AJAX implementation here
      // Replace this with your own implementation using XMLHttpRequest, jQuery, Axios, etc.
    }
  </script>
</body>
</html>

Tuesday, 27 June 2023

Laravel+inertia js +react install bootsrap and use


1)  install boostrap

npm install bootstrap


2) add below lines to bootstrap.js

import 'bootstrap/dist/css/bootstrap.css';

3) Within app.jsx add below line

import './bootstrap';



4) Optional
npm install jquery npm install @popperjs/core

Next, include the Bootstrap JavaScript files in the bootstrap.js file.
You can use the following lines to import jQuery, Popper.js, and the Bootstrap JavaScript:
Then add below lines to bootstrap.js
import 'jquery';
import 'popper.js/dist/popper';
import 'bootstrap/dist/js/bootstrap';

Laravel + inertia js + react progress bar setup

1) First, disable Inertia's default loading indicator. In app.jsx

createInertiaApp({
    progress: false,
    resolve: name => {
        const pages = import.meta.glob('./Pages/**/*.jsx', { eager: true })
        return pages[`./Pages/${name}.jsx`]
    },
    setup({ el, App, props }) {
        createRoot(el).render(<App {...props} />)
    },
})

 2) Next, install the NProgress library. 

npm install nprogress

3) add below link to app.blade.php

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/nprogress/0.2.0/nprogress.min.css" />

4) Your app.jsx

import './bootstrap';
import { createInertiaApp } from '@inertiajs/react'
import { createRoot } from 'react-dom/client'
import NProgress from 'nprogress' //for 4th step
import { router } from '@inertiajs/react' //for 4th step

createInertiaApp({
    progress: false, //for 1st step
    resolve: name => {
        const pages = import.meta.glob('./Pages/**/*.jsx', { eager: true })
        return pages[`./Pages/${name}.jsx`]
    },
    setup({ el, App, props }) {
        createRoot(el).render(<App {...props} />)
    },
})

router.on('start', () => NProgress.start()) //for 4th step
router.on('finish', () => NProgress.done()) //for 4th step



Friday, 16 June 2023

how to use multiple databases in laravel

 To use multiple databases in Laravel, you can configure multiple database connections in your Laravel application's configuration file (`config/database.php`). Here's a step-by-step guide:


1. Open the `config/database.php` file in your Laravel project.


2. Inside the `connections` array, define your additional database connections. You can add an array for each database connection you want to use. For example, let's assume we want to add a second database connection named "secondary". Here's how it can be added:


   ```

   'connections' => [

       'mysql' => [

           // Your default database connection configuration

       ],

   

       'secondary' => [

           'driver' => 'mysql',

           'host' => env('DB_SECONDARY_HOST', 'localhost'),

           'port' => env('DB_SECONDARY_PORT', '3306'),

           'database' => env('DB_SECONDARY_DATABASE', 'secondary_db'),

           'username' => env('DB_SECONDARY_USERNAME', 'root'),

           'password' => env('DB_SECONDARY_PASSWORD', ''),

           'charset' => 'utf8mb4',

           'collation' => 'utf8mb4_unicode_ci',

           'prefix' => '',

           'strict' => true,

           'engine' => null,

       ],

   

       // Other database connections...

   ],

   ```


   Adjust the connection details such as `host`, `port`, `database`, `username`, and `password` to match your secondary database configuration. You can also provide these values in your `.env` file for easier management.


3. Next, define the corresponding environment variables in your `.env` file for the secondary database connection. Add the following lines to your `.env` file:


   ```

   DB_SECONDARY_HOST=localhost

   DB_SECONDARY_PORT=3306

   DB_SECONDARY_DATABASE=secondary_db

   DB_SECONDARY_USERNAME=root

   DB_SECONDARY_PASSWORD=

   ```


   Modify the values according to your secondary database configuration.


4. Now that you have defined the second database connection, you can use it in your Laravel application. To specify which database connection to use, you can set the `connection` property on your Eloquent models or specify the connection explicitly in your queries.


   ```

   // Using the secondary database connection in a model

   protected $connection = 'secondary';

   ```


   ```

   // Using the secondary database connection in a query

   $users = DB::connection('secondary')->table('users')->get();

   ```


   By default, Laravel will use the connection defined in your `config/database.php` file for Eloquent models and queries if no explicit connection is specified.


With these steps, you can configure and use multiple databases in your Laravel application. You can define as many additional database connections as needed and use them by specifying the appropriate connection on your models or queries.

Prevent sql injection in php

 Preventing SQL injection is crucial to ensure the security and integrity of your application. Here are some best practices in PHP to prevent SQL injection:


1. Use Prepared Statements (Parameterized Queries):

   Prepared statements are one of the most effective ways to prevent SQL injection. Instead of directly embedding user input into SQL queries, placeholders are used, and the input values are bound separately. Prepared statements automatically handle escaping and sanitization, reducing the risk of injection attacks. Here's an example:


   ```

   $stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");

   $stmt->execute(['username' => $username]);

   $user = $stmt->fetch();

   ```


2. Input Validation and Sanitization:

   Validate and sanitize user input before using it in SQL queries. Ensure that input adheres to the expected format, length, and data type. Use functions like `filter_var` or custom validation methods to sanitize and validate input.


   ```

   $username = filter_var($_POST['username'], FILTER_SANITIZE_STRING);

   ```


3. Use ORM (Object-Relational Mapping):

   Consider using an ORM library like Laravel's Eloquent or Doctrine. These libraries provide abstraction layers that handle SQL injection prevention behind the scenes. They automatically sanitize and escape input, making it easier to write secure database queries.


4. Least Privilege Principle:

   Limit database user permissions to only what is required. Avoid using a database user with superuser privileges for regular application operations. Restrict access based on the principle of least privilege.


5. Escaping Special Characters:

   If you cannot use prepared statements, ensure that you escape special characters properly before incorporating them into SQL queries. In PHP, you can use the `mysqli_real_escape_string` function for MySQLi or `PDO::quote` for PDO to escape values.


   ```

   $username = mysqli_real_escape_string($conn, $username);

   ```


6. Avoid Dynamic Query Building:

   Avoid dynamically constructing SQL queries by concatenating user input. It can lead to injection vulnerabilities. If dynamic query construction is necessary, use proper sanitization techniques and parameter binding.


7. Limit Error Messages:

   Display generic error messages to users and log detailed error messages internally. Avoid exposing specific SQL error messages that might provide attackers with useful information about the database structure.


Remember, using prepared statements is generally the recommended approach to prevent SQL injection. These best practices, in combination with secure coding practices, can significantly mitigate the risk of SQL injection attacks in your PHP applications.

Laravel logout user if role changed by admin in active session of user

1) Create a new middleware that will check if the user's role has been changed and log them out if necessary. Run the following command to generate the middleware:

php artisan make:middleware CheckUserRole

2)Open the generated middleware file (app/Http/Middleware/CheckUserRole.php) and implement the handle method. The method should compare the user's current role with the role stored in the session. If they don't match, log out the user. Here's an example implementation:

<?php namespace App\Http\Middleware; use Closure; use Illuminate\Support\Facades\Auth; class CheckUserRole { public function handle($request, Closure $next) { if (Auth::check()) { $user = Auth::user(); // Check if the user's role has changed if ($user->role !== session('role')) { Auth::logout(); return redirect('/login')->with('message', 'Your role has been changed. Please log in again.'); } } return $next($request); } }

3) Register the middleware in the $routeMiddleware array of the app/Http/Kernel.php file. Add the following line to the array:

'role.check' => \App\Http\Middleware\CheckUserRole::class,

4)Apply the middleware to the relevant routes or route groups. For example, you can apply it to the routes that handle role changes:

Route::middleware('role.check')->group(function () { // Routes for changing user roles });

5)When an admin changes a user's role, update the user's role and update the role value stored in the user's session. You can accomplish this in your controller or wherever you handle the role change logic. Here's an example:

// Update the user's role $user->role = 'new_role'; $user->save(); // Update the role value in the session session(['role' => 'new_role']);

6) Open the RegisterController located at app/Http/Controllers/Auth/RegisterController.php.

Inside the create method, after the line that creates a new user, add the following code to set the user's role in the session:

// Create a new user $user = User::create([ 'name' => $data['name'], 'email' => $data['email'], 'password' => Hash::make($data['password']), ]); // Set the user's role in the session session(['role' => $user->role]);

7)Next, open the LoginController located at app/Http/Controllers/Auth/LoginController.php.

Inside the authenticated method, after the line that logs in the user, add the following code to set the user's role in the session:
Note: (authenticated method not present by default we need to create it.)

use Illuminate\Http\Request;

protected function authenticated(Request $request, $user) { // Log in the user // Set the user's role in the session session(['role' => $user->role]); // Redirect the user return redirect()->intended($this->redirectPath()); }


Thursday, 15 June 2023

Get device with using php

 function getScreenWidth() {

    $userAgent = $_SERVER['HTTP_USER_AGENT'];


    if (preg_match('/\b(?:iPhone|iPad|Android)\b/', $userAgent)) {

        // Mobile devices

        if (preg_match('/\bMobile\b/', $userAgent)) {

            // For mobile devices, the screen width is not available directly, but we can use JavaScript to get it.

            // You can include a JavaScript snippet in your HTML page and pass the value to PHP via AJAX.

            return null;

        } else {

            // Tablets

            if (preg_match('/\b(iPad)\b/', $userAgent)) {

                return 768; // Assume iPad width

            }

            

            // Other tablets

            return 1024; // Set a default tablet width

        }

    } else {

        // Desktop devices

        if (preg_match('/\bWindows\b/', $userAgent)) {

            // Windows desktop

            return 1920; // Set a default desktop width

        } elseif (preg_match('/\bMacintosh\b/', $userAgent)) {

            // Mac desktop

            return 2560; // Set a default desktop width

        } else {

            // Other desktop devices

            return 1366; // Set a default desktop width

        }

    }

}


// Usage

$screenWidth = getScreenWidth();

if ($screenWidth) {

    echo "Screen width: " . $screenWidth . "px";

} else {

    echo "Screen width is not available on mobile devices.";

}


Tuesday, 6 June 2023

Laravel + React , with Inertia and Vite setup

composer create-project laravel/laravel example-app

cd example-app

composer require inertiajs/inertia-laravel

Rename file resources/app/welcome.blade.php to the app.blade.php and paste the next code inside:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Laravel</title>

        @inertiaHead
@viteReactRefresh
@vite(['resources/css/app.css', 'resources/js/app.jsx'])
<!-- As you can see, we will use vite with jsx syntax for React-->
@inertiaHead
</head>
<body>
@inertia
</body>
</html>

After that we need to generate a middleware for Inertia by using the next command:

php artisan inertia:middleware

And to use the middleware that we just generated, open the app/Http/Kernel.php file and go to the web middleware group and add generated middleware to the web group:

'web' => [
// ...
\App\Http\Middleware\HandleInertiaRequests::class,
],


Client-side setup

Before we are going to write a first React component — we need to install all dependencies that we need for this tutorial:

npm install @inertiajs/inertia-react @inertiajs/react @vitejs/plugin-react react react-dom

After installation, we will need to configure Vite in our application so let’s do this in vite.config.js:


import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';
import react from '@vitejs/plugin-react';
export default defineConfig({
plugins: [
react(), // React plugin that we installed for vite.js
laravel({
input: ['resources/css/app.css', 'resources/js/app.jsx'],
refresh: true,
}),
],
});

Okay, and now we can configure the app.js file, but first let’s rename this file to the app.jsx:


import './bootstrap';

import { createInertiaApp } from '@inertiajs/react'

import { createRoot } from 'react-dom/client'


createInertiaApp({

  resolve: name => {

    const pages = import.meta.glob('./Pages/**/*.jsx', { eager: true })

    return pages[`./Pages/${name}.jsx`]

  },

  setup({ el, App, props }) {

    createRoot(el).render(<App {...props} />)

  },

})


ow we need to create a “Pages” folder inside the js folder, and inside this folder let’s create a test component named “Test.jsx”:


const Test = () => {
return (
<h1>This is test component</h1>
)
}
export default Test


Render component

We configured everything that we need to use React in our application and now it’s time to render the component that we just created, so let’s open routes/web.php and let’s try to render Test.jsx on the homepage:

<?php

use Illuminate\Support\Facades\Route;
use Inertia\Inertia; // We are going to use this class to render React components

Route::get('/', function () {
return Inertia::render('Test'); // This will get component Test.jsx from the resources/js/Pages/Test.jsx
});

Okay, and the final step — run the local server and run vite in the terminal:

php artisan serve

npm run dev

---------------------------------------------------------------------------

Reference links

Reference Link

Inertia doc

Laravel asset bundling








Laravel Export data to csv

 use Illuminate\Http\Response; // Define a function to export data to CSV function exportToCSV($exportData, $columns) {     $filename = ...