How to upload image in laravel 10 - WebJourney

How to upload image in laravel 10 - WebJourney

In Laravel we can easily upload  an image into database while we work in a project. In this tutorial we will learn how to uplaod an image as well as validate image mime types and size using laravel validation rules. Also display the validation error message as well as success flash message after save image into database.

 

We have the following steps to upload an image file into database.

 

 

1. Install a freash laravel project.

2. Create and setup database.

3. Create model and migration file

4.  Update migration file

5. Run migrate

6. Create require routes

7. Create ImageUploadController

8. Logic implements in controller.

9. Create View

10. Start development server and upload image

 

 

 

 

Step-1. Install a freash laravel project.

 

We can create a freash laravel project two ways first one is using laravel installer and another one is via composer. Using the bellow command we have to create a laravel project first.

//using laravel installer 
laravel new image-upload

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

 

 

 

Step-2. Create and setup database.


In this step we will create model, migration, controller, database and properly setup database credentials in .env file from our project . Now open .env file from your image-upload project and set database info (database name, user name and password) as show in bellow.

 

.env

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=image-upload
DB_USERNAME=root
DB_PASSWORD=

 

 

 

Step-3. Create model and migration file

Now we have to create a model also a migration file execute the bellow artisan code.

php artisan make:model ImageUpload -m

 

This command will create both ImageUpload model inside app\models folder and image_uploads_ migration file will be created at app\database\migrations folder.

 

 

 

 

Step-4. Update migration file

 

Now open migration file in a editor and add image field inside up() function as shown bellow.

 

image_uploads_migrations_

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('image_uploads', function (Blueprint $table) {
            $table->id();
            $table->string('image');
            $table->timestamps();
        });
    }

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

 

 

 

Step-5. Run migrate

 

Now run bellow artisan migrate command for create image_uploads table into database

php artisan migrate

 

Now open your ImageUpload model and add image filed in protected fillable array

 

ImageUpload.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class ImageUpload extends Model
{
    use HasFactory;
    protected $fillable = ['image'];
}

 

 

 

Step-6. Create require routes

 

Open web.php file from routes directory and make two routes. One is for image upload page and another one is for store image into database.

 

routes\web.php

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\ImageUploadController;


Route::get('/',[ImageUploadController::class,'upload-image'])->name('upload.image');
Route::post('/store-image',[ImageUploadController::class,'store_image'])->name('store.image');

 

 

 

Step-7. Create ImageUploadController

 

Run the bellow command to create controller:

php artisan make:controller ImageUploadController

 

 

 

 

Step-8. Logic implements in controller.

 

Here we define two methods first method is for image upload form and in second method is for validate image field and store image into database. Bellow is the full controller code.

 

Note: Create a folder images inside public folder and inside images create another folder uploads. Don't worry, if you don't want create any directory  these folders will automatically create in public directory. Just follow bellow code.

 

ImageUploadController.php

<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\ImageUpload;
use Session;

class ImageUploadController extends Controller
{

    public function image_upload()
    {
        return view('image_upload');
    }

    public function store_image(Request $request)
    {
        $request->validate([
            'image'=>'required|mimes:jpg,jpeg,png,bmp',
        ]);

        $imageName = '';
        if ($image = $request->file('image')){
            $imageName = time().'-'.uniqid().'.'.$image->getClientOriginalExtension();
            $image->move('images/uploads', $imageName);
        }
        ImageUpload::create([
            'image'=>$imageName,
        ]);
        Session::flash('message', 'New image added success.'); 
        Session::flash('alert-class', 'alert-success'); 
        return redirect()->back();
    }

}

 

 

 

 

Step-9. Create view

 

We will rename our welcome.blade.php file into image_upload.blade.php and design our form with the bellow code. For design our form we will use bootstrap cdn link.

 

image_upload.blade.php

<!doctype html>
<html lang="en">
<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <title>Laravel 10 Image Upload Tutorial By Web Journey</title>
</head>
<body>
<div class="container">
    <div class="row mt-3">
        <div class="col-md-12">
            <div class="card">
                <div class="card-header">
                    <div class="title" style="float:left;">
                        <h2 class="text-left">Add New Record</h2>
                    </div>
                </div>
                <div class="card-body">
                    @if ($errors->any())
                        <div class="alert alert-danger">
                            <ul>
                                @foreach ($errors->all() as $error)
                                    <li>{{ $error }}</li>
                                @endforeach
                            </ul>
                        </div>
                    @endif
                    @if(Session::has('message'))
                        <p class="alert {{ Session::get('alert-class', 'alert-info') }}">{{ Session::get('message') }}</p>
                    @endif

                    <form action="{{ route('store.image') }}" method="post" enctype="multipart/form-data">
                        @csrf
                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="mb-1">Image</label>
                                    <input type="file" name="image" class="form-control" value="{{ old('image') }}">
                                </div>
                            </div>
                            <button type="submit" class="btn btn-primary">Submit</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>

 

 

 

Step-10. Start development server and upload image

 

Start development server following the bellow command and test your application. Great works fine.

php artisan serve

 

Thanks. Hope it helps you a lot.

Tags

  • Share This: