You can upload image in Laravel 10 with proper validation. This won’t be a difficult job for handling image upload in Laravel 10. The mime type defines which type of file it will be going to allow while uploading. You can upload any kind of image and save the image name path into the database. So, that you can access it through the path in order to display that. In this post, we will be taking a look at the image upload in Laravel 10.
We are going to create an example of having image upload with the image validation. So, in the image validation basically, we will be checking mime type, file type and the max size.
If you select correct image and upload it then on success of upload, you will get the below message.
So, this was a glimpse of the today’s demo application. Now, let’s start by installing a Laravel 10 project.
Prerequisites
We are going to implement image upload functionality in Laravel 10. Hence, you need a Laravel 10 application. However, in order to create a Laravel 10 project, below tools and configurations are required.
- PHP >=8.1
- Composer
- Apache/Nginx Server
- VS Code Editor (Optional)
- MySQL (version > 5)
Once, you are done with the above requirement, let’s have a Laravel 10 project.
How to Create a CRUD Application Using Ajax in Laravel 10
Create a Project For Image Upload in Laravel 10
For installing Laravel 10, you need to hit the below command in the terminal. Then wait for a couple of minutes in order to finish the installation.
composer create-project --prefer-dist laravel/laravel image-upload
Once the project setup is done, let’s connect it to a database.
Create and Configure a Database
Firstly, you need to create a database in MySQL. Then after creating the database, let’s open the project in the editor and navigate to the .env file.
Now, under the DB section, just update the DB 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}}
After database configuration, you need to a model and migration.
How to Validate a Form Using Form Validator in Laravel 10
Create a Model and Migration in Laravel 10
For creating a model and migration, you can hit the below command.
php artisan make:model Image -mc
The command will create a model, a migration and a controller. Therefore, you need to add the schema inside the migration.
Now, navigate to the created migration, and add the below schema inside it.
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('images', function (Blueprint $table) {
$table->id();
$table->string('image_name')->nullable();
$table->string('image_original_name')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('images');
}
};
After adding the migration, you need to migrate the table using the below command.
php artisan migrate
The command will generate the table with added fields. Next, you need to add the fillable property in the model.
Add Fillable Property in Model in Laravel 10
You can add the fillable property so that based on this, you will able be save the values through the model in the database.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Image extends Model
{
use HasFactory;
protected $fillable = [
'image_name',
'image_original_name',
];
}
Next, we will start adding functionality for image upload in Laravel 10.
How to Create a CRUD Application in Laravel 10 For Beginners
Add Functionality For Laravel Image Upload
Open the controller (ImageController) and add the below snippet.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Image;
class ImageController extends Controller
{
/**
* Display a listing of the resource.
*/
public function create()
{
return view('image-upload');
}
/**
* Upload image and save image name.
*/
public function upload(Request $request) {
$request->validate([
'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
$image = time().'.'.$request->image->extension();
$imageOriginalName = $request->image->getClientOriginalName();
$request->image->move(public_path('uploads'), $image);
$image = Image::create([
"image_name" => $image,
'image_original_name' => $imageOriginalName,
]);
if ($image) {
return back()->with('success','Success! Image has been uploaded');
}
else {
return back()->with("failed", "Alert! Unable to upload image");
}
}
}
We have added the function for validating and uploading image.
Next, you need to add routes for executing the above functions.
Add Routes in Laravel 10
You have to add these routes in the web.php file.
<?php
use App\Http\Controllers\ImageController;
use Illuminate\Support\Facades\Route;
Route::get('image', [ImageController::class, 'create'])->name('image');
Route::post('image', [ImageController::class, 'upload'])->name('image.store');
After adding the route, you have to create a view with a form in which we will be adding file upload input.
Laravel 10 Released – Check Out Amazing Features of Laravel 10
Create a View For Image Upload
You need to create a view with the name image-upload.blade.php. After that you have to add the below snippet in it.
<!doctype html>
<html lang="en">
<head>
<title> Laravel 10 Image Upload with Validation - 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.store') }}" method="POST" enctype="multipart/form-data">
@csrf
<div class="card shadow">
<svg xmlns="http://www.w3.org/2000/svg" style="display: none;">
<symbol id="check-circle-fill" fill="currentColor" viewBox="0 0 16 16">
<path
d="M16 8A8 8 0 1 1 0 8a8 8 0 0 1 16 0zm-3.97-3.03a.75.75 0 0 0-1.08.022L7.477 9.417 5.384 7.323a.75.75 0 0 0-1.06 1.06L6.97 11.03a.75.75 0 0 0 1.079-.02l3.992-4.99a.75.75 0 0 0-.01-1.05z" />
</symbol>
<symbol id="exclamation-triangle-fill" fill="currentColor" viewBox="0 0 16 16">
<path
d="M8.982 1.566a1.13 1.13 0 0 0-1.96 0L.165 13.233c-.457.778.091 1.767.98 1.767h13.713c.889 0 1.438-.99.98-1.767L8.982 1.566zM8 5c.535 0 .954.462.9.995l-.35 3.507a.552.552 0 0 1-1.1 0L7.1 5.995A.905.905 0 0 1 8 5zm.002 6a1 1 0 1 1 0 2 1 1 0 0 1 0-2z" />
</symbol>
</svg>
{{-- Display alert message --}}
@if (Session::has('success'))
<div class="alert alert-success alert-dismissible d-flex align-items-center" role="alert">
<svg class="bi flex-shrink-0 me-2" width="24" height="24" role="img" aria-label="Success:">
<use xlink:href="#check-circle-fill" />
</svg>
<div>
{{ Session::get('success') }} <button type="button" class="btn-close" data-bs-dismiss="alert"
aria-label="Close"></button>
</div>
</div>
@elseif (Session::has('error'))
<div class="alert alert-danger d-flex alert-dismissible align-items-center" role="alert">
<svg class="bi flex-shrink-0 me-2" width="24" height="24" role="img" aria-label="Danger:">
<use xlink:href="#exclamation-triangle-fill" />
</svg>
<div>
{{ Session::get('error') }} <button type="button" class="btn-close" data-bs-dismiss="alert"
aria-label="Close"></button>
</div>
</div>
@endif
<div class="card-header">
<h4 class="card-title fw-bold"> Laravel 10 Image Upload with Validation</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-primary"> Upload </button>
</div>
</div>
</form>
</div>
</div>
</div>
</body>
</html>
We have added the form action to validate and upload the image. On success of image upload, the image will be moved to the public/uploads directory.
That’s it for the functionality. Now, you can run the application to check the result.
php artisan serve
That’s it for this post. I hope you will enjoy this and can implement it in your real project stuff.
Leave a Reply