Thursday, February 6, 2020

Laravel 6 - Save & Retrieve Images From The Mysql Database

Laravel 6 - Save & Retrieve Images From  The Mysql Database

Saving images in the MySQL database and then searching for images in the MySQL database under Laravel is a job for any web developer. In this post we learn how images are saved and retrieved from the MySql database. We learn these things in the context of Laravel 6. Since this is the latest version of the Laravel framework, every student wants to learn something in the latest version. Then, within Laravel 6, you will learn how to insert images into the MySQL database and then retrieve images from the MySQL database and display them on the website.

In this publication, we describe step-by-step how to insert images into the Mysql table in the Laravel 6 framework. Now you have the question why we have to save images in the database. This is because we can save images in the folder. So why do we have to store images in the database and why have we increased the size of our database? However, saving or inserting images into the database also has some advantages. An important advantage is that when a backup copy of our database was created, all of our images or file backups were also created at this time and we do not want to make a backup copy of the images separately.

Saving images in the database also has the advantage that all images have been saved in binary form and are only visible on the website. Here our pictures were saved because they are saved in binary form and not in their original form. Therefore storing images in the database offers many other advantages. Here in this publication we have not discussed the advantages of storing images in the database, but here we would like to discuss how images are stored and retrieved from the MySQL database as part of Laravel 6.

  1. Install Laravel 6 framework  by using command line
  2. Create Database Connection
  3. Build Model Class
  4. Download Image intercession Library
  5. Build Controller Class
  6. Build View Blade File
  7. Set Route
  8. Run Laravel Application

Install Laravel 6 Framework by using command line


If you want to use Laravel for your web application development. To do this, we first want to download the latest version of Laravel. To do this, at the command prompt, go to the directory where you want to download and install the Laravel framework and run the following command.


composer create-project --prefer-dist laravel/laravel laravel6


This command will make laravel6 folder and in that folder it will download latest version of Laravel framework.


Create Database Connection


To establish a database connection in the context of Laravel 6, we have to open the .env file. In this file we have to define the configuration details of the MySQL database, which you can find below.


DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=testing
DB_USERNAME=root
DB_PASSWORD=


Build Model Class


To save and retrieve images from the MySQL database, we use the Laravel Model class for the operation associated with the database. So we want to do the Model class first, for that we have to go to the command prompt and run the following command.


php artisan make:model Images -m


This command creates the Images.php model class in the application directory and also creates the table migration file in the database / migrations folder. First we need to open the migration file, which you can find in the database / migration folder and where you have to define the definition of the table column, which you can find 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->bigIncrements('id');
            $table->string('user_name');
            $table->binary('user_image');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('images');
    }
}




Here we added two table columns like user_name and user_image. Now we want to create a table in the MySQL database. To do this, we also need to go to the command prompt and run the following command.


php artisan migrate

This command creates a table with images in the MySQL database. Now we open the model class app / Images.php. In this class we have to define in which table the column data are filled in by the user, we have to define in the model class which can be found below.


<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Images extends Model
{
    protected $fillable = ['user_name', 'user_image'];
}


Download Image Intercession Library


Here we used the image intervention library for image manipulation. This library is an open source PHP image library for editing and editing images. This library also offers functions such as creating, editing and compiling images. First we want to download this library, for this we need to execute the following command.


composer require intervention/image

This command downloads this image intervention library. Here we used an additional package as part of Laravel, so we have to tell Laravel about this new package. To do this, we have to open config / app.php and define new package details.


'providers' => [

    // ...
      Intervention\Image\ImageServiceProvider::class,
    // ...
  ],
'aliases' => [
    // ...
      'Image'     => Intervention\Image\Facades\Image::class,
    // ...
  ],

In this way we can use an additional package as part of Laravel .

Build Controller Class


As part of Laravel, we need to create a controller class to handle the http request. To create a driver class file, we need to go to the command prompt and run the following command.


php artisan make:controller StoreImageController


This command creates the driver file StoreImageController.php in the app / Http / Controllers folder. In this controller class, we first have to import the following class into the header of this class.


use Illuminate\Support\Facades\Response;
use App\Images;
use Image;


Then we have the following method in the controller class.

index () - This is the root method of this class. It searches the image folder for data and is displayed in the file store_image.blade.php.

insert_image (Request $ request): After submitting the form, this method received data from the form to insert data into the MySQL database. With this method, first check whether the data comply with the validation rules or not. If you follow the validation rules, you need to add a process to the mysql table. Here the image was first saved in binary form in the MySQL database and then in the MySQL database.

fetch_image ($ image_id): This method first retrieves data from a single user based on the value of the primary key. The image is first retrieved from this data and then converted into binary data. As a result of this method, the image is returned.


<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Images;
use Illuminate\Support\Facades\Response;
use Image;

class StoreImageController extends Controller
{
    function index()
    {
     $data = Images::latest()->paginate(5);
     return view('store_image', compact('data'))
       ->with('i', (request()->input('page', 1) - 1) * 5);
    }

    function insert_image(Request $request)
    {
     $request->validate([
      'user_name'  => 'required',
      'user_image' => 'required|image|max:2048'
     ]);

     $image_file = $request->user_image;

     $image = Image::make($image_file);

     Response::make($image->encode('jpeg'));

     $form_data = array(
      'user_name'  => $request->user_name,
      'user_image' => $image
     );

     Images::create($form_data);

     return redirect()->back()->with('success', 'Image store in database successfully');
    }

    function fetch_image($image_id)
    {
     $image = Images::findOrFail($image_id);

     $image_file = Image::make($image->user_image);

     $response = Response::make($image_file->encode('jpeg'));

     $response->header('Content-Type', 'image/jpeg');

     return $response;
    }
}


Build View Blade File


As part of Laravel to display the HTML output on the website, you used the blade file that was saved in the resources / views folder. Here in this view file we did the following.


  • Write code to indicate the error validating the form data 
  • Write code to view the success message 
  • Create an HTML form to enter the name and select the profile picture
  • Create an HTML table to display dynamic data on the website


resources/views/store_image.blade.php


<html>
<head>
 <meta name="viewport" content="width=device-width, initial-scale=1">
 <title>Laravel 6 - Save & Retrieve Images From  The Mysql Database</title>
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
 <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
 <div class="container">    
  <br />
  <h3 align="center">Laravel 6 - Save & Retrieve Images From  The Mysql Database</h3>
    <br />
    @if($errors->any())
    <div class="alert alert-danger">
           <ul>
           @foreach($errors->all() as $error)
            <li>{{ $error }}</li>
           @endforeach
           </ul>
        </div>
    @endif

    @if(session()->has('success'))
     <div class="alert alert-success">
     {{ session()->get('success') }}
     </div>
    @endif
    <br />

    <div class="panel panel-default">
         <div class="panel-heading">
             <h3 class="panel-title">User Form</h3>
         </div>
         <div class="panel-body">
         <br />
         <form method="post" action="{{ url('store_image/insert_image') }}"  enctype="multipart/form-data">
          @csrf
          <div class="form-group">
          <div class="row">
           <label class="col-md-4" align="right">Enter Name</label>
           <div class="col-md-8">
            <input type="text" name="user_name" class="form-control" />
           </div>
          </div>
         </div>
         <div class="form-group">
          <div class="row">
           <label class="col-md-4" align="right">Select Profile Image</label>
           <div class="col-md-8">
            <input type="file" name="user_image" />
           </div>
          </div>
         </div>
         <div class="form-group" align="center">
          <br />
          <br />
          <input type="submit" name="store_image" class="btn btn-primary" value="Save" />
         </div>
         </form>
      </div>
     </div>
     <div class="panel panel-default">
         <div class="panel-heading">
             <h3 class="panel-title">User Data</h3>
         </div>
         <div class="panel-body">
         <div class="table-responsive">
                <table class="table table-bordered table-striped">
                  <tr>
                     <th width="30%">Image</th>
                     <th width="70%">Name</th>
                  </tr>
                  @foreach($data as $row)
                  <tr>
                   <td>
                    <img src="store_image/fetch_image/{{ $row->id }}"  class="img-thumbnail" width="75" />
                   </td>
                   <td>{{ $row->user_name }}</td>
                  </tr>
                  @endforeach
              </table>
              {!! $data->links() !!}
             </div>
         </div>
     </div>
    </div>
 </body>
</html>

Set Route


Before you run the Laravel application, you must first set the class method path of the Laravel controller. To do this, we have to open the routes / web.php file and set the path of the driver method.


Route::get('store_image', 'StoreImageController@index');

Route::post('store_image/insert_image', 'StoreImageController@insert_image');

Route::get('store_image/fetch_image/{id}', 'StoreImageController@fetch_image');

Here we have set the path of all controller class methods.

Run Laravel Application


When our code is ready, we now have to register in the browser. To do this we need to start the Laravel server, to do that we have to go to the command prompt and run the following command.


php artisan serve

This command starts the Laravel server and gives us the base URL of our Laravel application. To check the previous code, we need to write the following url into the browser.


http://127.0.0.1:8000/store_image

This is a complete step-by-step guide to inserting images into the MySQL database in the Laravel 6 framework and getting images from the MySQL table and displaying them on the website in the Laravel 6 application.

0 comments:

Post a Comment

Please don't enter any spam link in the comment box.