You can upload images in Laravel 8 with validation. The image uploading is a very common functionality in any form. You can implement Laravel 8 image upload functionality with a validation. In the image validation, you can check the file type, size, resolution, etc. The validation process makes a valid image upload. Today, in this post, I will be showing you the image upload guide in Laravel 8. Also, I will validate the image before uploading it. Then, I will save the file name into the database. So, let’s create a new project and start uploading an image.
Prerequisites
For creating the Laravel 8 image upload project, you will require the following tools with the specified version.
- PHP >= 7.3
- MySQL (version > 5)
- Apache/Nginx Server
- VS Code Editor
Create Project For Laravel 8 Image Upload
For creating a project, I will be using the composer. Open the terminal and command prompt and hit the below command.
composer create-project --prefer-dist laravel/laravel image-upload
Wait while the installation completes of this project.
Once, the project has been created, we will create and configure the database.
Laravel 8 CRUD Application Tutorial From Scratch
Create and Configure the Database
For the database, I will be using the MySQL. So, create a database there and then configure it for the Laravel project.
CREATE DATABASE image_upload;
For configuring the database in Laravel, navigate to .env file. Then add the database credentials there.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=image_upload
DB_USERNAME=root
DB_PASSWORD=root
Here, the database is synced with the project.
Create a Model, Migration, and Controller in Laravel 8
For storing the image name, we will require a model and the migration. The model will be synced with the table. The migration file will generate the schema of the table.
You can create a model, migration, and controller in a single line of command.
php artisan make:model Image -mc
In the above command, the model name is Image. Then -m denotes the migration and c denotes to the controller.
Now, we have the Image.php model. A migration named create_images_table.php. And a controller named ImageController.php.
Laravel 8 Form Validation Tutorial For Beginners
Add Fields in Migration
For newly created migration, we will add a field there. Basically, we will store the image name into the table. So, you will have to add the fields as showing below.
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateImagesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('images', function (Blueprint $table) {
$table->id();
$table->string('image_name');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('images');
}
}
Create Auth Using Jetstream and Intertia js in Laravel 8
Add Fillable Data in Image Model
For the above field, we will have to add the fillable data in the model. So, here the specified field name will sync with the table.
<?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"
];
}
In the next step, we will migrate the schema.
php artisan migrate
The above command will migrate the tables.
Once the table is migrated, let’s add the functionality for the image upload.
Firstly, we will call a view inside the function.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Image;
class ImageController extends Controller
{
public function index() {
return view('image-upload');
}
}
Laravel 7 Yajra DataTable with Server Side Processing
Add Route
At this time, I will add a route for the above function.
<?php
use App\Http\Controllers\ImageController;
use Illuminate\Support\Facades\Route;
Route::get('image', [ImageController::class, 'index']);
Then create a view to get the input of the image.
Create a View For Uploading Image
For uploading the image, we will have to create a view. So, I am going to create a view named image
<!doctype html>
<html lang="en">
<head>
<title> Laravel 8 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://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>
<body>
<div class="container mt-5">
<div class="row">
<div class="col-xl-6 m-auto">
<form action="{{url('image/upload')}}" 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="close" data-dismiss="alert">×</button>
{{Session::get('success')}}
</div>
@elseif(Session::has('failed'))
<div class="alert alert-success alert-dismissible">
<button type="button" class="close" data-dismiss="alert">×</button>
{{Session::get('failed')}}
</div>
@endif
<div class="card-header">
<h4 class="card-title"> Laravel 8 Image Upload </h4>
</div>
<div class="card-body">
<div class="form-group">
<label> Image </label>
<input type="file" name="image" class="form-control">
{!!$errors->first('image', '<span class="text-danger">:message</span>')!!}
</div>
</div>
<div class="card-footer">
<button type="submit" class="btn btn-success"> Upload </button>
</div>
</div>
</form>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</body>
</html>
After running the application, you will have the below layout.
Now, we will be reading the image from this view. So, for reading out the image from the view, add the below function in the ImageController.php.
// ---------- [ Upload image ] ---------
public function uploadImage(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(["image_name" => $image]);
if(!is_null($image)) {
return back()->with('success','Success! image uploaded');
}
else {
return back()->with("failed", "Alert! image not uploaded");
}
}
Now, add a route for the above function.
Route::post('image/upload', [ImageController::class, 'uploadImage']);
Save and run the application and choose the file for uploading. So, at very first, I have chosen a zip file.
Then when I clicked on the upload button, it returned the validation error message.
When the validation pass, you will have the success message. Here, you can see the result of the image upload.
How to Use Http Client For Request Handling in Laravel 7
Conclusion
Laravel 8 Image upload has been achieved successfully. Before uploading the Image, we have validated it. So, that every image will be uploaded as per our specified rules. In the next post, we will see How to upload Multiple Images in Laravel 8.
David Syengo says
I was having the same issue with Laravel 8 and it turns out on the UI side the enctype was not set on the form. Thanks for the tutorial.