laravel

Complete Laravel 8 Image upload Tutorial with example


Imagine you have a web application and it doesn’t contain any image. It’s quite unreal, right? Image is an integral part of your application that simulates visual perception of what are you really trying to say or present.

Every programming language or framework has functionality that allows image upload and storage. In Laravel, we can do it as well.

In this article, you are going to learn about how to upload an image in Laravel 8. There are many ways to upload an image. But you’re going to learn the simplest way to do it. We’re going to find out step by step Laravel 8 Image upload tutorial with example.

Prerequisite :

To complete this tutorial all you need to have is a configured computer, a text editor, a web browser, a web server installed on your computers like Xampp or WampServer, composer(package manager), and a basic understanding of PHP and laravel.

In this tutorial, we will use Sublime Text 3 as a text editor, xampp server, and Google Chrome as a web browser.

Steps To Upload An Image In Laravel

  • Download Laravel 8 application
  • Setup Database
  • Create Model & Migration
  • Create Routes
  • Create Controller
  • Create Blade View
  • Create Image Directory
  • Run Development Server

Download Laravel 8 application

In order to upload an image, first of all, we need to download and set up a laravel application. With composer installed on your computer, you can download a laravel project with the following command-

composer create-project laravel/laravel laravel-image-upload

Setup Database

Now the project is installed, you need to set up the database to store the data. You need to find out the .env file on your laravel project and set up the database name. Like this-

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel-image-upload
DB_USERNAME=your_database_username
DB_PASSWORD=your_database_password

Create Model & Migration

As we know, laravel follows the model-view-controller(MVC) pattern, we need to create a model. Models are objects that create relationships with a database table. You can create a model and migration file at a time with this php artisan command.

php artisan make:model Postimage -m

Here Postimage is the model name and -m command means creating a migration file. Tough, you can create them separately if you want. Now the migration file is created, you’ll find that file under the database/migrations folder and the file name is create_postimages_table.php.

public function up()
    {
        Schema::create('postimages', function (Blueprint $table) {
            $table->id();
            $table->string('image')->nullable();
            $table->integer('created_by')->nullable();
            $table->integer('updated_by')->nullable();
            $table->timestamps();
        });
    }

You can add many fields you want to your database table. Now you need to migrate it to the database following this artisan command.

php artisan migrate

Create Routes

Now we need to make routes. In laravel routes makes a relationship with your laravel controller. In your installed laravel project there is a file called web.php. Routes are written in that file. We need to create three routes for this project in this article to add, store, and view the image. Like this-

//For adding an image
Route::get('/add-image',[ImageUploadController::class,'addImage'])->name('images.add');

//For storing an image
Route::post('/store-image',[ImageUploadController::class,'storeImage'])
->name('images.store');

//For showing an image
Route::get('/view-image',[ImageUploadController::class,'viewImage'])->name('images.view');

Create Controller

After creating the routes, now we need a controller. The controller is a class where we handle requests, implement logic. In your laravel project, they are stored in the app/Http/Controllers directory. You can use the php artisan command to create a controller-

php artisan make:controller ImageUploadController

In this example, we’re going to use the name ImageUploadController. Inside the controller, you’ll need three functions to add, store and view the data-

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;

class ImageUploadController extends Controller
{
    //Add image
    public function addImage(){
        return view('add_image');
    }
    //Store image
    public function storeImage(){
       /*Logic to store data*/
    }
		//View image
    public function viewImage(){
        return view('view_image');
    }
}

Here in the controller, addImage() and viewImage() functions returns blade files.

Create Blade View

Now we’ve our routes, controller and model, we need to create blade files to add and display images. For adding the image-

//add_image.blade.php
<div class="container">
  <form method="post" action="{{ route('images.store') }}" 
		enctype="multipart/form-data">
    @csrf
    <div class="image">
      <label><h4>Add image</h4></label>
      <input type="file" class="form-control" required name="image">
    </div>

    <div class="post_button">
      <button type="submit" class="btn btn-success">Add</button>
    </div>
  </form>
</div>

Here is the HTML code for adding data to a database through the form. Inside the form, we have an input field that takes images as files and a submit button for submitting the data. When you are going to upload an image to a database in laravel remember you must have to use (enctype=”multipart/form-data”). Otherwise, it’ll not work. Our, method is “post” because we’re inserting data not getting. Be careful about that. And in the action, we’re going to define the route name where we put our data storing functionality.

Create Images Directory

When we upload an image to the database, it is the image path that is stored in the database. So, you need to create a folder under the public folder of your project. Like public/Image.

After adding the image, now we’ve to store it. Here is the code for storing the data:

/*You've to use the database model name from your App\Models folder at the top of
 your controller page*/
use App\Models\Postimage;

//Store image
    public function storeImage(Request $request){
        $data= new Postimage();

        if($request->file('image')){
            $file= $request->file('image');
            $filename= date('YmdHi').$file->getClientOriginalName();
            $file-> move(public_path('public/Image'), $filename);
            $data['image']= $filename;
        }
        $data->save();
        return redirect()->route('images.view');
       
    }

At first, The Request function returns the current request instance or obtains an input item from the user or you can say the form that we created in the “add_image” page. Then we call the Postimage model and store the result to a variable. Then we check a condition if our $request variable contains or does not, the specific file name in that case “image”. Then we concatenate with date function and GetClientOriginalName(). The function GetClientOriginalName() is used to retrieve the file’s original name at the time of upload in laravel. Then we move the filename to a path and the path will be stored in the database. After that, we just simply use the save() method to save the data to the database.

Now the data is stored in the database, we can view the data to the user interface which is very easy. The code to view the images from the database is given below:

//View post
    public function viewImage(){
        $imageData= Postimage::all();
        return view('Image.view_image', compact('imageData'));
    }

In this function, we’ve used all() function to get all the images from the database by using the “Postimage” model and passing the retrieved data into the “view_image” HTML page through a compact function. Here is the HTML code to view the images:

<div class="container">
    <h3>View all image</h3><hr>
    <table class="table">
      <thead>
        <tr>
          <th scope="col">Image id</th>
          <th scope="col">Image</th>
        </tr>
      </thead>
      <tbody>
        @foreach($imageData as $data)
        <tr>
          <td>{{$data->id}}</td>
          <td>
	     <img src="{{ url('public/Image/'.$data->image) }}"
 style="height: 100px; width: 150px;">
	  </td>
        </tr>
        @endforeach
      </tbody>
    </table>
  </div>

In the view page, we looped through the retrieved data by using @foreach loop statement and viewing the images.

Run Development Server

Now run the development server with the following PHP artisan command-

php artisan serve

OUTPUT(Add image):

Laravel 8 Image upload

OUTPUT(View all the images):

Laravel 8 Image upload

Conclusion:

In this tutorial, we learned how to upload an image in laravel with examples. Though, there are several ways to upload images. But this is one of the simplest ways to do it.


Share on social media

//