Laravel 8 Multiple Image Upload and store in mysql database
To upload and store multiple images in Laravel 8 using a MySQL database, you can follow these steps:
- Create a migration file to add an image column to your database table.
php artisan make:migration add_images_to_posts_table --table=posts
- Edit the newly created migration file located in
database/migrations
folder. Add the following code inside theup()
method:
Schema::table('posts', function (Blueprint $table) {
$table->string('image_path')->nullable();
$table->string('image_path_2')->nullable();
// Add more image columns as needed
});
- Run the migration to update the database schema:
php artisan migrate
- Create a form in your view file to allow users to upload multiple images. You can use Laravel's built-in file input field with multiple attribute:
<form action="/posts" method="POST" enctype="multipart/form-data">
@csrf
<input type="file" name="images[]" multiple>
<button type="submit">Upload</button>
</form>
- In your controller, handle the file upload and store the images in a public folder or a dedicated folder using Laravel's
Storage
facade:
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
public function store(Request $request)
{
$request->validate([
'images.*' => 'image|mimes:jpeg,png,jpg,bmp,gif,svg,pdf,doc,docx,xls,xlsx,odt,ods,odp,pot,potx,pps,ppsx,ppt,pptx,txt,csv,xml,zip,rar,7z,mp3,wav,mp4,mov,avi,wmv,mpeg,flv,swf,ogg,ogv,webp,jpeg,png'
]);
$post = new Post();
if ($request->hasFile('images')) {
foreach ($request->file('images') as $image) {
$imageName = time() . '_' . $image->getClientOriginalName();
$image->storeAs('public/uploads', $imageName);
$post->image_path = $imageName;
}
}
$post->save();
return redirect()->back();
}
- Update your model to access the image paths:
public function getImagePathAttribute()
{
return $this->image_path;
}
public function getImagePath2Attribute()
{
return $this->image_path_2;
}
- In your view file, display the images using the image path attributes:
<img src="{{ $post->image_path }}" alt="Image 1">
<img src="{{ $post->image_path_2 }}" alt="Image 2">
That's it! You've now implemented multiple image upload and storage in Laravel 8 using a MySQL database.