You can upload image in Laravel 9 with validation. For validating the image there are built-in validation rules. This validation will help you to check the file type, size, format, etc. You can write the custom validation as well. It totally depends upon the requirement. The same validation can be applied to the different file types. Generally, the file has a mime type. So, by checking the mime type, you can validate the file extension. In this post, we will see the image upload in Laravel 9.
So, at the end of this post, we will achieve the below results.
If the validation will fail, you will have the below result.
On successful upload, you will get the success response.
Form Validation in Laravel 9 with Custom Error Messages
So, let’s dive into the post by creating a new project setup.
Prerequisites
For creating a new application in Laravel 9, you will need to follow the below requirements.
- PHP >=8.0.2
- Composer
- Apache/Nginx Server
- VS Code Editor (Optional)
- MySQL (version > 5)
Create Project in Laravel 9
You can install Laravel 9 using the below command. Once, the project is ready, you can move for the image upload in Laravel 9.
composer create-project --prefer-dist laravel/laravel blog
After creating the project, let’s configure a database for it.
Create and Configure Database
At very first, you will require to have a database. Once, it is ready, let’s configure it with the Laravel 9 application. Navigate to the root of the project folder. Find the .env file and update the database credentials as shown below.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=DATABASE_NAME
DB_USERNAME=DATABASE_USERNAME
DB_PASSWORD=DATABASE_PASSWORD
In the next step, create a model and migration.
How to Create a CRUD Application in Laravel 9 From Scratch
Create a Model and Migration to Upload Image Laravel 9
We will create a model, a migration, and a controller as well. So, all the files will be created using the below command.
php artisan make:model Image -mc
After creating the files, let’s switch to the image migration file. Here, we will add the schema for the table.
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('images', function (Blueprint $table) {
$table->id();
$table->string('imageName');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('images');
}
};
Here, I have added only one field to store the uploaded image name. You can add more fields as you required.
Now, let’s migrate the table for dumping the schema in the database.
php artisan migrate
After successful migration, the database will have a table with the above schema.
How to Create a Dependent Dropdown in Laravel 9 Using Ajax
Add Fillable Data in Model
Navigate to the Image.php (model) and add the fillable property as shown below.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Image extends Model
{
use HasFactory;
protected $fillable = [
'imageName'
];
}
Finally, in the next step, we will move to the functionality of image upload in Laravel 9.
Add Functionality to Upload Image in Laravel 9
Navigate to the ImageController and add the below snippets.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Image;
class ImageController extends Controller
{
/**
* Return image upload view
* @param request
* @return response
*/
public function index() {
return view('image-upload');
}
/**
* Upload image
* @param request
* @return response
*/
public function upload(Request $request) {
$request->validate([
'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
$image = time().'.'.$request->image->extension();
$request->image->move(public_path('uploads'), $image);
$image = Image::create(["imageName" => $image]);
if ($image) {
return back()->with('success','Success! image uploaded');
}
else {
return back()->with("failed", "Alert! image not uploaded");
}
}
}
In the next step, add the routes for the above functions.
How to Resolve 419 Page Expired Issue in Laravel 9
Add Routes For Image Upload in Laravel 9
For adding routes, navigate to the web.php file. Now, add the below routes.
<?php
use App\Http\Controllers\ImageController;
use Illuminate\Support\Facades\Route;
Route::get('image', [ImageController::class, 'index'])->name('image');
Route::post('image', [ImageController::class, 'upload'])->name('image');
At last, you have to create a view for uploading the image.
Create a View For Image Upload
For uploading an image, you will require to have a form with an input type of file. So, create a new blade file with the name image-upload.blade.php.
After creating the blade file, you have to add the below snippet.
<!doctype html>
<html lang="en">
<head>
<title> Laravel 9 Image Upload - Programming Fields</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
</head>
</head>
<body>
<div class="container mt-5">
<div class="row">
<div class="col-xl-6 col-md-6 col-sm-12 m-auto">
<form action="{{ route('image') }}" method="POST" enctype="multipart/form-data">
@csrf
<div class="card shadow">
@if(Session::has('success'))
<div class="alert alert-success alert-dismissible">
<button type="button" class="btn-close" data-dismiss="alert">×</button>
{{Session::get('success')}}
</div>
@elseif(Session::has('failed'))
<div class="alert alert-danger alert-dismissible">
<button type="button" class="btn-close" data-dismiss="alert">×</button>
{{Session::get('failed')}}
</div>
@endif
<div class="card-header">
<h4 class="card-title fw-bold"> Laravel 9 Image Upload </h4>
</div>
<div class="card-body">
<div class="form-group">
<label> Image </label>
<input type="file" name="image" class="form-control @error('image') is-invalid @enderror ">
@error('image')
<div class="invalid-feedback">{{$message}}</div>
@enderror
</div>
</div>
<div class="card-footer">
<button type="submit" class="btn btn-success"> Upload </button>
</div>
</div>
</form>
</div>
</div>
</div>
</body>
</html>
That’s it for the functionality. Now, you can run the application and test the result.
How to Integrate CKEditor 4 in Laravel 9 With File Upload
Conclusion
We achieved the image upload result in Laravel 9. While uploading an image, we checked for the required field and the chosen file type. So, it was a validation for the image. That’s it for the post. We will see multiple image upload with validation in the next post. So, stay tuned with Programming Fields.
Leave a Reply