Thursday, 21 September 2023

laravel unique validation, except self , ignore self or current row

 public function rules(): array
    {
        return [
            'title' => [
                'required',
                Rule::unique(Category::class, 'title')->ignore($this->id, 'id'),
                'max:255'
            ],
            'slug' => [
                'required',
                Rule::unique(Category::class, 'slug')->ignore($this->id, 'id'),
                'max:255'
            ],
            'image' => 'nullable|image|mimes:jpeg,png,jpg,gif|max:2048',
        ];
    }

Wednesday, 20 September 2023

laravel make image thumbnail intervantion

 if ($request->hasFile('image')) {
            $ds = DIRECTORY_SEPARATOR;
            $image = $request->file('image');

            // Validate the uploaded image
            $validatedData = $request->validate([
                'image' => 'required|image|max:2048', // Max size in KB (2MB)
            ]);

            try {
                // Store the original image in the public directory
                $imageName = $image->hashName();
                $imagePath = $image->move(public_path('admin' . $ds . 'uploads' . $ds . 'category_images'), $imageName);

                // Create a resized thumbnail (100x100 pixels)
                $thumbnailName = $imageName;
                $thumbnailPath = public_path("admin" . $ds . "uploads" . $ds . "category_thumbnails");
                if (!file_exists($thumbnailPath)) {
                    mkdir($thumbnailPath, 0777, true);
                }

                $thumbnail = Image::make($imagePath)
                    ->fit(100, 100);
                $thumbnail->save($thumbnailPath . "" . $ds . "" . $thumbnailName);

                // Destroy the Intervention Image instance to free up memory
                $thumbnail->destroy();

                $thumbnailPath = $thumbnailPath . "" . $ds . "" . $thumbnailName;

                $validatedData['image'] = $imagePath;
                $validatedData['thumbnail'] = $thumbnailPath;

                return redirect()->back()->with('status', 'Created successfully');
            } catch (\Exception $e) {
                return redirect()->back()->with('status', 'An error occurred while processing the image.');
            }
        }

Wednesday, 6 September 2023

laravel react inertia, show images

 If you want to define the base URL for serving images from the `public` folder in a central place so that you can easily update it if needed, you can create a configuration file or a JavaScript variable to store the base URL. Here's how you can do that:


**Option 1: Define a JavaScript variable:**


In your Laravel project, you can create a JavaScript file (e.g., `config.js`) where you define the base URL for serving images. For example:


```javascript

// config.js


const IMAGE_BASE_URL = '/images/';

export default IMAGE_BASE_URL;

```


Then, in your React components, you can import this variable and use it to construct image URLs:


```jsx

import React from 'react';

import IMAGE_BASE_URL from './config'; // Adjust the import path accordingly


function ImageDisplay() {

    // Construct image URL using the base URL

    const imageUrl = `${IMAGE_BASE_URL}image.jpg`;


    return (

        <div>

            <img src={imageUrl} alt="Image" />

        </div>

    );

}


export default ImageDisplay;

```


This way, you can easily change the base URL for images by updating the `config.js` file.


**Option 2: Define a configuration file in Laravel:**


Alternatively, you can define a configuration variable in Laravel to store the base URL for serving images. Here's how you can do that:


1. Create a custom configuration file in Laravel by running the following command:


```bash

php artisan make:config image

```


This will create a new configuration file at `config/image.php`.


2. In the `config/image.php` file, define the base URL for serving images:


```php

<?php


return [

    'base_url' => '/images/',

];

```


3. In your Laravel application, you can access this configuration value using the `config()` function and pass it to your Inertia views:


```php

// In your controller

use Illuminate\Support\Facades\Config;


public function index()

{

    $imageBaseUrl = Config::get('image.base_url');


    return inertia('YourViewName', [

        'imageBaseUrl' => $imageBaseUrl,

    ]);

}

```


4. In your Inertia.js view component, you can then use this `imageBaseUrl` to construct image URLs:


```jsx

import React from 'react';

import { usePage } from '@inertiajs/inertia-react';


function ImageDisplay() {

    const { imageBaseUrl } = usePage();


    // Construct image URL using the base URL

    const imageUrl = `${imageBaseUrl}image.jpg`;


    return (

        <div>

            <img src={imageUrl} alt="Image" />

        </div>

    );

}


export default ImageDisplay;

```


This approach allows you to configure the base URL for serving images directly in your Laravel configuration files, making it easy to manage and update.



Within HandleInertiaRequest middleware


 return array_merge(parent::share($request), [
            'auth' => [
                'user' => $request->user(),
            ],
            'ziggy' => function () use ($request) {
                return array_merge((new Ziggy)->toArray(), [
                    'location' => $request->url(),
                ]);
            },
            'asset_url'=>Config::get('app.asset_url'),
        ]);





IN React page

import { usePage } from '@inertiajs/react';
 const { asset_url } = usePage().props;

  <img src={`${asset_url}backend/dist/img/AdminLTELogo.png`} alt="AdminLTE Logo" />

Laravel Export data to csv

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