How to upload image in laravel 10

How to upload image in larawel 10

Laravel 10 image upload; In this tutorial, we will learn how to upload image to MySQL database and storage directory with validation in Laravel 10 app. And also, how to validate image mime type, size, dimensions, etc on laravel controller using laravel validation rules.

  1. Create a new Laravel 10 project using Composer:
composer create-project laravel/laravel your-project-name --prefer-dist
  1. Change to the project directory:
cd your-project-name
  1. Create a new migration for the images table:
php artisan make:migration create_images_table
  1. In the new migration file, add the following code to create the images table:
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateImagesTable extends Migration
{
    public function up()
    {
        Schema::create('images', function (Blueprint $table) {
            $table->id();
            $table->string('filename');
            $table->string('path');
            $table->integer('size');
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('images');
    }
}
  1. Run the migration to create the images table:
php artisan migrate
  1. Create a new model for the Image:
php artisan make:model Image
  1. In the new model file, add the following code to define the table and its fillable attributes:
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Image extends Model
{
    use HasFactory;

    protected $table = 'images';

    protected $fillable = [
        'filename',
        'path',
        'size',
    ];
}
  1. Create a new controller for the Image:
php artisan make:controller ImageController
  1. In the new controller file, add the following code to define the index method to display the images:
use App\Models\Image;

public function index()
{
    $images = Image::orderBy('created_at', 'desc')->get();
    return view('images.index', ['images' => $images]);
}
  1. Create a new view for the images index:
touch resources/views/images/index.blade.php
  1. In the new view file, add the following code to display the images:
@if (count($images) > 0)
    <ul>
        @foreach ($images as $image)
            <li>
                <img src="{{ asset($image->path) }}" alt="Uploaded image">
                <div>{{ $image->filename }}</div>
                <div>{{ $image->size }} bytes</div>
            </li>
        @endforeach
    </ul>
@endif
  1. Create a new route for the images index:
Route::get('/images', [ImageController::class, 'index'])->name('images.index');
  1. Create a new view for the image upload form:
touch resources/views/images/upload.blade.php
  1. In the new view file, add the following code to display the image upload form:
<form action="{{ route('images.upload') }}" method="POST" enctype="multipart/form-data">
    @csrf
    <input type="file" name="image">
    <button type="submit">Upload</button>
</form>
  1. Create a new route for the image upload form:
Route::get('/images/upload', function () {
    return view('images.upload');
})->name('images.upload.form');
  1. Create a new route to handle the image upload:
Route::post('/images/upload', [ImageController::class, 'upload'])->name('images.upload');
  1. In your ImageController file, add the following code to define the upload method to handle the image upload:
use App\Models\Image;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

public function upload(Request $request)
{
    $request->validate([
        'image' => 'required|image|mimes:jpeg,png,jpg,gif|max:2048',
    ]);

    $image = $request->file('image');
    $filename = $image->getClientOriginalName();
    $path = $image->store('public/images');
    $size = $image->getSize();

    $image = new Image([
        'filename' => $filename,
        'path' => $path,
        'size' => $size,
    ]);
    $image->save();

    return redirect()->route('images.index')
        ->with('success','Image has been uploaded successfully.');
}
  1. This code validates that the image is required, an image file, of the allowed mime types, and is no larger than 2MB. If the validation passes, it uploads the file to the public/images folder in your storage system, saves the image data to the database, and redirects back to the images index page.
  2. Now, you need to configure the storage system in your Laravel project. Open the .env file and set the FILESYSTEM_DRIVER to public:
FILESYSTEM_DRIVER=public
  1. Also, add a new public disk in your config/filesystems.php file:
'disks' => [
    //...
    'public' => [
        'driver' => 'local',
        'root' => public_path('storage'),
        'url' => env('APP_URL').'/storage',
        'visibility' => 'public',
    ],
],
  1. Run the following command to create a symlink to the storage directory:
php artisan storage:link
  1. Now, you can access the images in the public/images folder using the asset() helper function.
  2. In your ImageController file, add a use statement for the Illuminate\Support\Facades\Storage facade.
  3. If you want to display the images from the storage system, you can update your index method in your ImageController:
use App\Models\Image;
use Illuminate\Support\Facades\Storage;

public function index()
{
    $images = Image::orderBy('created_at', 'desc')->paginate(10);
    return view('images.index', ['images' => $images]);
}
  1. This code retrieves all images from the database and uses the asset() helper function to display the images from the public/images folder.
  2. If you want to delete an image from your storage system, you can add a delete method to your ImageController:
use App\Models\Image;
use Illuminate\Support\Facades\Storage;

public function delete(Image $image)
{
    Storage::disk('public')->delete($image->path);
    $image->delete();

    return redirect()->route('images.index')
        ->with('success','Image has been deleted successfully.');
}
  1. This code deletes the image file from your storage system and deletes the image record from the database.
  2. In your view, you can add a delete button for each image:
@if (count($images) > 0)
    <ul>
        @foreach ($images as $image)
            <li>
                <img src="{{ asset($image->path) }}" alt="Uploaded image">
                <div>{{ $image->filename }}</div>
                <div>{{ $image->size }} bytes</div>
                <form action="{{ route('images.delete', $image
  1. In the delete form, add a CSRF token and use the HTTP DELETE method:
<form action="{{ route('images.delete', $image->id) }}" method="POST">
    @csrf
    @method('DELETE')
    <button type="submit">Delete</button>
</form>
  1. Finally, add a success message to your index view to show when an image is deleted:
@if (session('success'))
    <div class="alert alert-success">
        {{ session('success') }}
    </div>
@endif

Congratulations! You have successfully implemented image upload, storage, and deletion in your Laravel 10 application.

This Article Ideas has been taken from the following websites; which are following:

Laravel 10 Image Upload Example Tutorial

Laravel 10 Image Upload Example Tutorial

Laravel 10 CRUD and Image Upload Tutorial with Laravel Breeze and Repo Example

How to Upload Image Using Laravel 10?

Laravel 10 Image Upload With Preview Example

How to Upload Image in Laravel 10 with Validation

Laravel 10 Image Upload And Display Tutorial

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *