<!DOCTYPE html>
Thursday, 29 June 2023
Css Loader on ajax call
Tuesday, 27 June 2023
Laravel+inertia js +react install bootsrap and use
Laravel + inertia js + react progress bar setup
1) First, disable Inertia's default loading indicator. In app.jsx
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
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
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:$routeMiddleware array of the app/Http/Kernel.php file. Add the following line to the array: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:RegisterController located at app/Http/Controllers/Auth/RegisterController.php.create method, after the line that creates a new user, add the following code to set the user's role in the session:LoginController located at app/Http/Controllers/Auth/LoginController.php.authenticated method, after the line that logs in the user, add the following code to set the user's role in the session: authenticated method not present by default we need to create it.)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
Laravel Export data to csv
use Illuminate\Http\Response; // Define a function to export data to CSV function exportToCSV($exportData, $columns) { $filename = ...
-
download source code.zip from below link https://github.com/fideloper/TrustedProxy/releases extract the zip open vendor folder create a ne...
-
if ( $request -> hasfile ( 'project_nda' )) { if ( $SalesClosure -> project_nda != "" &...
-
1) Install Laravel excel in laravel existing project https://docs.laravel-excel.com/3.1/getting-started/installation.html 2)Create new clas...