AI Reading
Quick summary of this article
This tutorial explains how to build a simple image upload system in Laravel 11. It walks through creating a database model and migration to store image information, building a controller to handle uploads with validation, and setting up Blade templates for the upload form and image display. Images are stored in the public/uploads folder, and their paths are saved in the database.
- Create an Image model and migration with fields for title and image_path, then run the migration to set up the database table.
- Build an ImageController with methods to show all images, display the upload form, and handle the store request with validation for file type (jpeg, png, jpg, gif) and size (max 2MB).
- Store uploaded images in the public/uploads directory using a unique timestamp-based filename, and save the path to the database.
- Define three routes: one for the image list, one for the upload form, and one POST route to handle the upload submission.
- Create two Blade templates: a form with title and file inputs, and a gallery view that loops through images and displays each with its title and a 200px-wide thumbnail.
Introduction
Uploading images is a common requirement in web applications. Laravel 11 makes it easy to handle image uploads with its built-in validation, file storage, and Eloquent ORM features.
In this tutorial, we will learn how to upload images in Laravel 11. We will cover:
- Setting up Laravel 11
- Creating a model and migration
- Building a controller for handling image uploads
- Validating and storing images
- Displaying uploaded images
By the end of this guide, you will have a fully functional image upload system.
Setting Up Laravel 11
Make sure you have Laravel 11 installed. If not, install it using Composer:
composer create-project --prefer-dist laravel/laravel laravel11upload
Navigate to your project directory:
cd laravel11upload
Creating a Model and Migration
We need a database table to store image paths. Let’s create a model along with a migration:
php artisan make:model Image -m
Open the generated migration file in database/migrations/ and update the up method:
public function up()
{
Schema::create('images', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->string('image_path');
$table->timestamps();
});
}
Run the migration to create the table:
php artisan migrate
Creating the Image Model
Modify the Image.php model located in app/Models/Image.php:
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Image extends Model
{
use HasFactory;
protected $fillable = ['title', 'image_path'];
}
This model allows mass assignment for title and image_path fields.
Creating a Controller
Generate a controller for handling image uploads:
php artisan make:controller ImageController
Modify ImageController.php in app/Http/Controllers/:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Image;
class ImageController extends Controller
{
public function index()
{
$images = Image::all();
return view('images.index', compact('images'));
}
public function create()
{
return view('images.create');
}
public function store(Request $request)
{
$request->validate([
'title' => 'required',
'image' => 'required|image|mimes:jpeg,png,jpg,gif|max:2048',
]);
$imageName = time() . '.' . $request->image->extension();
$request->image->move(public_path('uploads'), $imageName);
Image::create([
'title' => $request->title,
'image_path' => 'uploads/' . $imageName,
]);
return redirect()->route('images.index')->with('success', 'Image uploaded successfully');
}
}
Defining Routes
Update routes/web.php to include routes for image upload:
use App\Http\Controllers\ImageController;
Route::get('images', [ImageController::class, 'index'])->name('images.index');
Route::get('images/create', [ImageController::class, 'create'])->name('images.create');
Route::post('images', [ImageController::class, 'store'])->name('images.store');
Creating Blade Templates
Image Upload Form
Create resources/views/images/create.blade.php:
@extends('layouts.app')
@section('content')
<h1>Upload Image</h1>
<form action="{{ route('images.store') }}" method="POST" enctype="multipart/form-data">
@csrf
<input type="text" name="title" placeholder="Image Title" required>
<input type="file" name="image" required>
<button type="submit">Upload</button>
</form>
@endsection
Display Uploaded Images
Create resources/views/images/index.blade.php:
@extends('layouts.app')
@section('content')
<h1>Uploaded Images</h1>
@foreach ($images as $image)
<div>
<h2>{{ $image->title }}</h2>
<img src="{{ asset($image->image_path) }}" width="200" alt="{{ $image->title }}">
</div>
@endforeach
@endsection
Required Blade Files
Ensure you have the following Blade files in resources/views/images/:
create.blade.php– Form for uploading images.index.blade.php– Displays uploaded images.layouts/app.blade.php– A layout file containing common structure and styling.
Summary
In this tutorial, we covered Laravel 11 image upload functionality. We:
- Created a model and migration for storing image paths
- Built a controller to handle image upload logic
- Implemented validation for uploaded images
- Stored images in the
public/uploadsdirectory - Displayed uploaded images on the frontend
By following these steps, you now have a fully functional image upload system. You can further enhance it by adding authentication, resizing images, or integrating a cloud storage service like AWS S3.
Happy coding! 🚀
