Upload Image in Laravel 5

Hello world, this tutorial is about how to upload image in laravel 5. In this tutorial, we will create simple example with upload image in folder and then save that image in database table. I have divided this tutorial in following parts:

  • Setup laravel 5 on xampp server
  • Setup controller, view and route
  • Upload image in folder
  • Setup database, model and migration
  • Save image in database table

Setup Laravel 5 on Xampp Server

First of all we will set up laravel 5 on xampp server. I am using window operating system so that I am using xampp server. You can install any server according to your running operating system. In this tutorial I am using visual studio for coding. This is my personal choice. You can use any of your favorite code editors like sublime or atom. So let’s start to set up laravel 5 on xampp server.

  • Open visual studio code
  • Enter ctrl+~
  • You will see the command prompt in the bottom area.
  • Go to xampp/htdocs/ folder
  • Open the command prompt and run the following command
  • composer create-project laravel/laravel upload

I have assumed that you have installed composer. If you don’t know about composer then please follow this link to know about composer and install composer on your system because without composer you cannot install laravel

Laravel installation process may take some time to install. After successful installation, open server with laravel folder on your browser and then go to public folder. You will see the following screen.


Setup Controller, views and route for this application

After the successful installation of laravel 5 we will create controller, views and setup route for this application.

  • Create upload controller
    • Open command line and go to upload folder.
    • Run the following command to create controller
    • php artisan make:controller UploadController
    • Open /app/Http/Controllers/UploadController.php
    • Create index method in the UploadController class and add the following code the in this method.
// Upload Image Screen
    function index(){
        return view('upload');
    }
    // Upload Image
    function submit_form(Request $request){
        $request->validate([
            'img' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048'
        ]);
        $image = $request->file('img');
        $imageName=time().'.'.$image->getClientOriginalExtension();
        $destinationPath = public_path('/imgs');
        $image->move($destinationPath, $imageName);
        return redirect('upload')->with('success','Image has been successfully updated.');
    }
  • Create View for uploading image
    • Create upload.blade.php in resources/views/ folder.
    • Add the following code in this file.
<!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>Uploade Image With Laravel</title>
    {{-- Bootstrap 4 --}}
    <link rel="stylesheet" href="{{ asset('lib/bootstrap.min.css') }}">
</head>
<body>
    <div class="container mt-4">
        <div class="row">
            <div class="col-sm-12">
                @if($errors->any())
                    @foreach($errors->all() as $e)
                        <p class="alert alert-danger">{{ $e }}</p>
                    @endforeach
                @endif
                @if(Session::has('success'))
                <p class="alert alert-success">{{ session('success') }}</p>
                @endif
                <a href="http://projectsplaza.com"><img src="{{ asset('imgs/projectsplazadotcom.png') }}" /></a>
                <div class="card mt-3">
                    <div class="card-header">Upload Image</div>
                    <div class="card-body">
                        <form action="{{ url('upload') }}" method="post" enctype="multipart/form-data">
                            {{ csrf_field() }}
                            <table class="table table-bordered">
                                <tr>
                                    <th>Upload Image</th>
                                    <td>
                                        <input type="file" name="img">
                                    </td>
                                </tr>
                                <tr>
                                    <td colspan="2">
                                        <input type="submit" value="Upload" class="btn btn-danger" />
                                    </td>
                                </tr>
                            </table>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
</html>
  • Set up route
    • Open /routes folder and edit the php file.
    • Add the following code in this file.
Route::get('/upload','UploadController@index');
Route::post('/upload','UploadController@submit_form');

Open the project in the bowser with public path like the following. You will see the following screen.

http://localhost/laravel-apps/upload/public/upload

 

Create imgs folder in public folder. Now try to submit the form. if you see the success message then it means you have successfully uploaded the image in the folder. For more confirmation, you can check the imgs folder.


Save image in Database

We have successfully uploaded image in the folder. Now we will add the image in dataTable table.

Setup database and model for saving image in the database

  • Create upload database in your phpmyadmin
  • Open .env file from your root
  • Add database name, server name, password, database name in this file.
  • Run the following command to create model and table

php artisan make:model Upload –m

  • After running this command,open /database/migrations/some_date_uploads_table.
  • Replace the following code with previous code in up() function.
Schema::create('uploads', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('img_src');
            $table->timestamps();
        });

 

  • Run this command to create the table in database
    • php artisan migrate
    • Go to your database, you will see the tables.
  • Now it’s time to change the controller code to save the image in table.
  • We will save image name in img_src column that we have just created.
  • Add the following code in the upload controller just before the class start.
  • use App\Upload
  • Add the following code in the upload controller just before the return redirect code.
  • // Save Image in the database
            $img=new Upload;
            $img->img_src=$imageName;
            $img->save();

     

  • Now run the application.

Leave a Reply