How to Install Laravel 11 Globally : A Step-by-Step Guide
Read More
In this tutorial, I will walk you through a Laravel 10 image upload example. We will explore the process of uploading images in a Laravel 10 application. This example is designed to guide you on how to upload images to the database using Laravel 10. We'll go into detail on how to upload and display images in a Laravel 10 project.
Throughout this tutorial, we will create two routes – one for the GET method and another for the POST method. We'll set up a straightforward form with a file input field, making it easy for users to select an image. The chosen image will be uploaded to the 'images' directory within the public folder of your Laravel project. So, follow along with the steps below to learn how to effortlessly implement image uploads in your Laravel 10 application.
See the preview of this tutorial on how to upload and display images in Laravel 10:
In this first step, we need a fresh Laravel 10 application for the laravel 10 image upload and display. So download it by the below command:
composer create-project laravel/laravel example-app
We are going to use the User
model. Now update by adding an image uploading system which means an image column to the users table like below:
php artisan make:model Post -mc
<?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('posts', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->string('image_name')->nullable();
$table->string('image_type')->nullable();
$table->string('image_size')->nullable();
$table->string('image_path')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('posts');
}
};
Now in this step, we have to already created a PostController to define this method to create a laravel image upload example.
<?php
namespace App\Http\Controllers;
use App\Models\Post;
use App\Traits\ImageUpload;
use Illuminate\Http\Request;
class PostController extends Controller
{
use ImageUpload;
public function store(Request $request)
{
$data = $request->all();
$path = "user/profile/";
if ($file = $request->file('image')) {
$fileData = $this->uploads($file, $path);
$data['image_path'] = $fileData['filePath'];
$data['image_size'] = $fileData['fileSize'];
$data['image_type'] = $fileData['fileType'];
$data['image_name'] = $fileData['fileName'];
}
Post::create($data);
return back()->with('success', 'Successfully Store Image');
}
public function update(Request $request)
{
$existingPhoto = Post::find($id)->photo;
$userPhotoPath = "user/profile/";
if ($file = $request->file('photo')) {
$fileData = $this->uploads($file, $userPhotoPath, $existingPhoto);
$data['photo'] = $fileData['filePath'];
}
}
}
In this controller, we have used the ImageUpload
trait to handle the image upload process. It extracts the image file from the request, saves it to the specified path, and stores relevant information in the database.
To make this approach work, you need the "ImageUpload" trait. This trait streamlines the image upload process and encapsulates the logic for reuse in different parts of your application. Here is the "ImageUpload" trait:
<?php
namespace App\Traits;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
trait ImageUpload
{
public function uploads($file, $path, $existingFile = null)
{
if ($existingFile) {
Storage::disk('public')->delete($existingFile);
}
if ($file && $file->isValid()) {
$unqRan = Str::random(20);
$fileName = time() . $unqRan . $file->getClientOriginalName();
Storage::disk('public')->putFileAs($path, $file, $fileName);
$file_name = $file->getClientOriginalName();
$file_type = $file->getClientOriginalExtension();
$filePath = $path . $fileName;
return [
'fileName' => $file_name,
'fileType' => $file_type,
'filePath' => $filePath,
'fileSize' => $this->fileSize($file)
];
}
return null;
}
public function fileSize($file, $precision = 2)
{
$size = $file->getSize();
if ($size > 0) {
$size = (int) $size;
$base = log($size) / log(1024);
$suffixes = array(' bytes', ' KB', ' MB', ' GB', ' TB');
return round(pow(1024, $base - floor($base)), $precision) . $suffixes[floor($base)];
}
return $size;
}
}
This trait consists of two main functions:
uploads($file, $path, $existingFile = null)
: This function manages the upload of image files. It also allows you to replace an existing file if necessary and returns valuable information about the uploaded file.
fileSize($file, $precision = 2)
: This auxiliary function helps calculate the file size in a human-readable format, such as KB, MB, GB, etc.
In your Laravel project, create a Blade view that allows users to upload images. Here's a sample Blade view that you can use:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>how to add image in laravel 10</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container mt-5">
<div class="row">
<div class="col-md-8">
<div class="card">
<div class="card-header">
<h3>How to make Generic Method to add image in laravel 10</h3>
</div>
<div class="card-body">
<form action="{{ route('post.store') }}" method="post" enctype="multipart/form-data">
@csrf
<div class="form-group">
<label for="exampleFormControlFile1">Title</label>
<input class="form-control" type="text" name="title" placeholder="Enter Title">
</div>
<div class="form-group">
<label for="exampleFormControlFile1">image</label>
<input type="file" name="image" class="form-control-file"
id="exampleFormControlFile1">
</div>
<button type="submit" class="btn btn-primary float-right">Submit</button>
</form>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-8">
<div class="card mb-5">
<div class="card-header">
<h3>List</h3>
</div>
<div class="card-body">
<table class="table">
<thead class="thead-dark">
<tr>
<th scope="col">#</th>
<th scope="col">Title</th>
<th scope="col">Image </th>
<th scope="col">Type</th>
<th scope="col">Image Name</th>
<th scope="col">Size</th>
</tr>
</thead>
<tbody>
@foreach ($posts as $post)
<tr>
<th scope="row">{{$post->id}}</th>
<td>{{$post->title}}</td>
<td><img src="{{Storage::url($post->image_path)}}" alt="" width="100" height="100"></td>
<td>{{$post->image_type}}</td>
<td>{{$post->image_name}}</td>
<td>{{$post->image_size}}</td>
</tr>
@endforeach
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
Now all are set to go. Now run php artisan serve
command to start the development server and visit the following URL to check this laravel image upload tutorial. Don't forget to run this command php artisan storage:link
and then visit:
In this tutorial, we've explored how to simplify image uploads in Laravel 10 by creating a generic "ImageUpload" function. This approach allows you to handle image uploads consistently and efficiently across your Laravel projects, promoting code reusability and maintainability.
By implementing a generic image upload method, you can streamline your development process, ensure consistency in your code, and provide a user-friendly experience for your application's users. Whether it's user avatars, product images, or any other type of media, this approach makes handling image uploads in Laravel a breeze.
Recent posts form our Blog
0 Comments
Like 0