DEV Community

Cover image for Tutorial for Laravel 8 Image Upload Example
Code And Deploy
Code And Deploy

Posted on

3 2

Tutorial for Laravel 8 Image Upload Example

Originally posted @ https://codeanddeploy.com visit and download the sample code: https://codeanddeploy.com/blog/laravel/tutorial-for-laravel-8-image-upload-example

In this post, I will share an example of how to upload an image on Laravel 8. When developing a Laravel application the functionality of uploading images is always there. Usually, we require our users to upload their profile photos for some verification purposes. Or a gallery module for your Laravel application. So in this example, I will show to you an example about Laravel image upload.

tutorial-for-laravel

Step 1: Laravel Installation

If you don't have a Laravel 8 install in your local just run the following command below:



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


Enter fullscreen mode Exit fullscreen mode

Step 2: Create Controller

Next, we will create a controller for our Laravel image upload. Run the following artisan command:



php artisan make:controller ImageUploadController


Enter fullscreen mode Exit fullscreen mode

Step 3: Create Routes

Next, we will add our routes. Navigate routes/web.php the add the following code.



<?php

use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::group(['namespace' => 'App\Http\Controllers'], function()
{   
    Route::get('/image-upload', 'ImageUploadController@index')->name('image-upload.index');
    Route::post('/image-upload', 'ImageUploadController@upload')->name('image-upload.post');
});


Enter fullscreen mode Exit fullscreen mode

Step 4: Setup Controller Methods

Now lets, create our method of our Laravel image upload controller.



<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests\ImageUploadRequest;

class ImageUploadController extends Controller
{
    public function index() 
    {
        return view('image-upload.index');
    }

    public function upload(ImageUploadRequest $request) 
    {
        $filename = time() . '.' . $request->image->extension();

        $request->image->move(public_path('images'), $filename);

        // save uploaded image filename here to your database

        return back()
            ->with('success','Image uploaded successfully.')
            ->with('image', $filename); 
    }
}


Enter fullscreen mode Exit fullscreen mode

Step 5: Create Laravel Image Upload Request

Next, we will add our validation request. Run the following command:



php artisan make:request ImageUploadRequest


Enter fullscreen mode Exit fullscreen mode

Step 6: Add View

Next, we will add our view for our image upload index.blade.php. Navigate the directory resources/views/ then create an image-upload folder.

Then create file index.blade.php see below code:



<!DOCTYPE html>
    <html>

    <head>
        <meta charset="utf-8" />
        <meta name="csrf-token" content="{{ csrf_token() }}">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title>Laravel 8 Image Upload Example - codeanddeploy.com</title>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"></script>
    </head>

    <body>
        <div class="container mt-5">
            @if(Session::get('success', false))
              <?php $data = Session::get('success'); ?>
              @if (is_array($data))
                  @foreach ($data as $msg)
                      <div class="alert alert-success" role="alert">
                          <i class="fa fa-check"></i>
                          {{ $msg }}
                      </div>
                  @endforeach
              @else
                  <div class="alert alert-success" role="alert">
                      <i class="fa fa-check"></i>
                      {{ $data }}
                  </div>
              @endif

              <img src="images/{{ Session::get('image') }}" width="200px">
            @endif

            <form action="{{ route('image-upload.post') }}" method="POST" enctype="multipart/form-data">
                @csrf
                <div class="row">

                    <div class="col-md-6">
                        <input type="file" name="image" class="form-control">
                        @if ($errors->has('image'))
                            <span class="text-danger text-left">{{ $errors->first('image') }}</span>
                        @endif
                    </div>

                    <div class="col-md-6">
                        <button type="submit" class="btn btn-success">Upload</button>
                    </div>

                </div>
            </form>
        </div>
    </body>
</html>


Enter fullscreen mode Exit fullscreen mode

Now test it. Run command below:



php artisan serve


Enter fullscreen mode Exit fullscreen mode

Then hit this URL to your browser: http://127.0.0.1:8000/image-upload

Now you have a simple functionality to upload images in Laravel 8. I hope this tutorial can help you. Kindly visit here https://codeanddeploy.com/blog/laravel/tutorial-for-laravel-8-image-upload-example if you want to download this code.

Happy coding :)

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more