How to Handle Image Uploads in Laravel
At first install Laravel by following official documentation.
Create a Model and Migration for Image Upload:
php artisan make:model Product -m
This will create a Product
model and corresponding migration file. Open the migration file (database/migrations/YYYY_MM_DD_create_products_table.php
) and add a column for the image:
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->text('description');
$table->string('image')->nullable();
$table->timestamps();
});
}
Then, run the migration to create the products
table:
php artisan migrate
Create form for image upload:
Create a form in view to allow users to upload images and add other product details.
<form action="{{url('admin/add-products')}}" method="POST" enctype="multipart/form-data">
@csrf
<label for="name">Product Name:</label>
<input type="text" name="name" id="name">
<label for="description">Description:</label>
<textarea name="description" id="description"></textarea>
<label for="image">Image:</label>
<input type="file" name="image" id="image">
<button type="submit">Submit</button>
</form>
Store Uploaded Image:
In ProductController
, store the image in the public
directory and save image path in the database.
use App\Models\Product;
use Illuminate\Http\Request;
public function store(Request $request)
{
$request->validate([
'name' => 'required',
'description' => 'required',
'image' => 'required|image|mimes:jpeg,png,jpg,gif|max:2048',
]);
$product = new Product;
$product->name = $request->name;
$product->description = $request->description;
if($request->hasfile('image')){
$file = $request->file('image');
$filename = time() . '.' . $file->getClientOriginalExtension();
$file->move('uploads/product/', $filename);
$product->image = $filename;
}
$product->save();
return redirect('admin/product')->with('message', 'Product Added Successfully');
}
Display Uploaded Image:
In view where you display product details, you can display the uploaded images:
<img src="{{asset('uploads/product/'.$item->image)}}" alt="Image">
Validation and Error Handling:
Make sure to handle validation errors and display them to the user if the form submission fails.