PART-1
PART-2
PART-3

Concept

  • Image path will be uploaded to database table.
    • Example: adil.jpg
  • Actual image is uploaded to some folder inside our project folder.
    • Example: public/assets/images.

Validation

  1. Required
  2. Image Extension -> jpg, jpeg and png only
  3. Image Size -> Should be less than 1 MB

Step: 1

  • Create the project by using this command.
    • Laravel new [project_name]

Step: 2

  • Create the Controller by using this command.
    • Php artisan make:controller HomeController

Step: 3

  • Create a function in HomeController.

Step: 4

  • That function returns a view, which display a form in which we upload the image, so now create a view and form for uploading the image.
  • Note: Don’t Forget to add @csrf token inside the form.

Step: 5

  • Create the Database in PhpMyAdmin and add that database information in .env file present in laravel project folder.

Step: 6

  • Create the Model class with migration by using this command.
    • Php artisan make:model ModelName -m

Step: 7

  • Setting up the default length of String in App\Providers\AppServiceProvider.php file.
    • Add this namespace AppServiceProvider.php file
    • use Illuminate\Support\Facades\Schema;
    • Now write below line in boot function present inside AppServiceProvider.php
    • Schema::defaultStringLength(191);

Step: 8

  • Now Run The Migration by using this command
    • Php artisan migrate
  • Important Point: When you create another migration for a table then you need to just execute above command and that table will automatically created in database.
  • You can follow above point if you are working with several tables time to time.

Step: 9

  • Add namespace of your model class in your controller.
  • Example: use App/Models/Model_Class

Step: 10

  • Create a folder to hold images in public directory of your laravel project.
  • Example: Public/assets/images

Step: 11

  • Now create a function in controller to store images into the database and to the public/assets/images folder.

Complete Source Code Down Below:

HomeController Code

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Student;

class HomeController extends Controller
{
    public function Index()
    {
        return view('Home.Index');
    }

    public function ShowImage()
    {
        $data = Student::all();
        return view('Home.ShowImage',compact('data'));
    }

    public function Store(Request $req)
    {
        $req->validate([
            'std_name' => 'required',
            'std_image' => 'required | image | mimes:jpg,jpeg,png,PNG | max:1024'
        ], 
        [
            'std_image.image' => 'Image Extension Should be jpg,jpeg and png only',
            'std_image.max' => 'Image Size Should be less than 1 MB'
        ]);

        $obj = new Student();
        $obj->student_name = $req->input('std_name');
        
        if($req->hasfile('std_image'))
        {
            $img = $req->file('std_image');
            $name = $img->getClientOriginalName();
            $fileName = 'public/assets/images/'. $name;
            $img->move('public/assets/images/', $fileName);
            $obj->student_image = $fileName;
        }
        $obj->save();
        // return redirect()->back()->with('status','Image Uploaded Successfully');
        // return redirect()->back()->with('status',$fileName);
        return redirect()->action("App\Http\Controllers\HomeController@ShowImage")->with('status','Image Uploaded Successfully');

    }
}

Index.blade.php – Form View Code

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <form action="{{ url('upload') }}" method="post" enctype="multipart/form-data">
    @csrf
    <label>Enter Name: </label>
    <input type="text" name="std_name" ><br>
    @error('std_name')
    <span style="color:red;"> {{ $message }} </span>
    @enderror
    <br>
    <label>Select Image: </label>
    <input type="file" name="std_image" ><br>
    @error('std_image')
    <span style="color:red;"> {{ $message }} </span>
    @enderror
    <br>
    <input type="submit" value="Upload">
    </form>
    @if(session('status'))
    {{--<!-- <h5 style="color:green;">{{ session('status') }}</h5> -->--}}
    <img src="{{ session('status') }}" height="150" width="150" alt="">
    @endif

</body>
</html>

Model Class Code – Student Model Class

<?php

namespace App\Models;

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

class Student extends Model
{
    use HasFactory;
    protected $table = 'students';
    protected $fillable = ['student_name','student_image'];
}

Student Migration File Code

<?php

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

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

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

AppServiceProvider.php File Code

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Schema;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        Schema::defaultStringLength(191);
    }
}

Web.php – Routes File 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::get('/', function () {
//     return view('welcome');
// });

Route::get('/','App\Http\Controllers\HomeController@Index');
Route::post('upload','App\Http\Controllers\HomeController@Store');
Route::get('ShowImage','App\Http\Controllers\HomeController@ShowImage');

.env File Code

APP_NAME=Laravel
APP_ENV=local
APP_KEY=base64:p82TpNZVxoAK3NS/53pUOAR2kZMWg3mE5GraAoJ7RC4=
APP_DEBUG=true
APP_URL=http://ImageUploadDemo.test

LOG_CHANNEL=stack
LOG_DEPRECATIONS_CHANNEL=null
LOG_LEVEL=debug

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=imageuploaddb
DB_USERNAME=root
DB_PASSWORD=

BROADCAST_DRIVER=log
CACHE_DRIVER=file
FILESYSTEM_DRIVER=local
QUEUE_CONNECTION=sync
SESSION_DRIVER=file
SESSION_LIFETIME=120

MEMCACHED_HOST=127.0.0.1

REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379

MAIL_MAILER=smtp
MAIL_HOST=mailhog
MAIL_PORT=1025
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null
MAIL_FROM_ADDRESS=null
MAIL_FROM_NAME="${APP_NAME}"

AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=
AWS_DEFAULT_REGION=us-east-1
AWS_BUCKET=
AWS_USE_PATH_STYLE_ENDPOINT=false

PUSHER_APP_ID=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=
PUSHER_APP_CLUSTER=mt1

MIX_PUSHER_APP_KEY="${PUSHER_APP_KEY}"
MIX_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"

Table Structure & Data

ShowImage.blade.php Source Code

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>

@if(session('status'))
    <h5 style="color:green;">{{ session('status') }}</h5>
    @endif
    <table border="2">
    <tr>
        <th>ID</th>
        <th>NAME</th>
        <th>IMAGE</th>
    </tr>

    @foreach($data as $item)
    <tr>
        <td>{{ $item->id }}</td>
        <td>{{ $item->student_name }}</td>
        <td><img src="{{ asset($item->student_image) }}" height="100" width="100"></td>
    </tr>
    @endforeach

    </table>
</body>
</html>

Click Below Link to Download Source Code Of This Blog

https://www.mediafire.com/file/57w781qwt10jd09/ImageUploadDemo.rar/file

Click Below Link to Download Notes Of This Blog

https://www.mediafire.com/file/nhr3tdxkqxl68jg/IMAGE+UPLOADING.zip/file

No responses yet

Leave a Reply

Your email address will not be published. Required fields are marked *