In this article, I will show you how to image upload in laravel 12 application. Laravel 12 Image Upload Example
In this tutorial, we will create two routes: one for the GET method to render forms and another for the POST method to upload image code. We created a simple form with a file input. So, you have to simply select an image, and then it will upload in the “images” directory of the public folder.
So, you simply have to follow the below steps to upload an image in a Laravel 12 application. You Can Learn Laravel 12 CRUD Application Example Tutorial
Laravel 12 Image Upload Example
Step 1: Install Laravel 12
This step is not required; however, if you have not created the Laravel app, then you may go ahead and execute the below command:
laravel new example-app
Step 2: Create Controller
In this step, we will create a new ImageController
. In this file, we will add two methods: index()
and store()
, for rendering views and storing image logic.
Let’s create the ImageController
by following this command:
php artisan make:controller ImageController
Next, let’s update the following code to the controller file.
app/Http/Controllers/ImageController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\View\View;
use Illuminate\Http\RedirectResponse;
class ImageController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index(): View
{
return view('imageUpload');
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function store(Request $request): RedirectResponse
{
$request->validate([
'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
$imageName = time().'.'.$request->image->extension();
$request->image->move(public_path('images'), $imageName);
/*
Write Code Here for
Store $imageName name in DATABASE from HERE
*/
return back()->with('success', 'Image uploaded successfully!')
->with('image', $imageName);
}
}
Store Image in Storage Folder
$request->image->storeAs('images', $imageName);
// storage/app/images/file.png
Store Image in Public Folder
$request->image->move(public_path('images'), $imageName);
// public/images/file.png
Store Image in S3
$request->image->storeAs('images', $imageName, 's3');
Step 3: Create and Add Routes
Furthermore, open routes/web.php
file and add the routes to manage GET and POST requests for rendering views and storing image logic. Read More
Top comments (0)