DEV Community

Cover image for Laravel 12 image Upload in public folder with preview
itstuffsolutions
itstuffsolutions

Posted on

Laravel 12 image Upload in public folder with preview

Laravel 12 image Upload with preview in this post, I’ll guide you how to upload an image to the public folder in a Laravel 12 application. follow these steps:
Step 1: Install Laravel 12
Step 2: Create Controller
Step 3: Create Routes
Step 4: Create Blade File
Step 5: Run Laravel App
Step 1: Install Laravel 12
create a new laravel project by running the following command:

laravel new laravel-image-upload
Enter fullscreen mode Exit fullscreen mode

** Step 2:Create the Controller**

In this step, create a new controller called ImageController. In this file, we will add two methods: index() and postImage(),for front view and uploading image logic. you can also learn Complete Laravel 12 Custom Login and Registration Tutorial for Beginners

Type below command to create ImageController:

php artisan make:controller ImageController
Enter fullscreen mode Exit fullscreen mode

Next step, update the following code to the Image
Controller file. laravel image upload example

app/Http/Controllers/ImageController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Str;

class ImageController extends Controller
{
    public function index()
    {
        return view('image');
    }

    public function postImage(Request $request){
         $request->validate([
            'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048 |dimensions:min_width=100,max_width=500',
        ]);
        $imageName = time(). '_' . Str::random(10).'.'.$request->image->extension();
        //store file in public folder
        $request->image->move(public_path('uploads'), $imageName);
       //store file in storage folder
       //$path = $request->file('image')->storeAs($imageName);


        return back()->with('success', 'Image uploaded successfully!');
    }
}

Enter fullscreen mode Exit fullscreen mode

Image Validation

  1. required: Image is required.
  2. image: checks the uploaded file is an actual image.
  3. mimes: Accepts only specific image types (jpeg, png,svg etc.). 4.max:2048: Maximum Limits size to 2MB (in kilobytes). 5.dimensions: Enforces image width between 100px and 500px.
  4. You can remove unnecessary image validation rules if they are not needed.

Store Image in Storage Folder


2
//store file in storage folder
$path = $request->file('image')->storeAs($imageName);
Enter fullscreen mode Exit fullscreen mode

write this code to upload laravel image in storage folder read more

Top comments (0)