DEV Community

Chitt Ranjan Mahto (Chirag)
Chitt Ranjan Mahto (Chirag)

Posted on

Laravel 12 Webcam Capture Image and Save from Webcam & display with MySQL Database

inchirags@gmail.com Chirag's Laravel Tutorial https://www.chirags.in


Laravel 12 Webcam Capture Image and Save from Webcam & display with MySQL Database


Step 1: Install Laravel

composer create-project --prefer-dist laravel/laravel laravel_12_webcam
Step 2: Create Controller

php artisan make:controller WebcamController
Step 3: Create Route

//routes/web.php

<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\WebcamController;
/*
|--------------------------------------------------------------------------
| 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('webcam', [WebcamController::class, 'index']);
Route::post('webcam', [WebcamController::class, 'store'])->name('webcam.capture');
Route::get('photo/{id}', [WebcamController::class, 'photo']);
Enter fullscreen mode Exit fullscreen mode

Step 4: Configuration MySQL database in .env file

//.env

DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=laravel_12_webcam
DB_USERNAME=root
DB_PASSWORD=admin@123
Enter fullscreen mode Exit fullscreen mode

Step 5: Create database with the name of laravel_12_webcam in MySQL Database.

Step 6: Update Migration and Model

In this step, we will add the "photo" column in the user's table and model.

//database/migrations/xxxxxxx_create_users_table.php

<?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('users', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email');
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->string('photo_name');  // new column
            $table->rememberToken();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('users');
    }
}
Enter fullscreen mode Exit fullscreen mode

Step 7: Execute the migration by using the following command.

php artisan migrate
Step 8: Update the User model.

//app/Models/User.php

<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;

    protected $fillable = [
        'name',
        'email',
        'password',
        'photo_name',
    ];

    protected $hidden = [
        'password',
        'remember_token',
    ];

    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

}
Enter fullscreen mode Exit fullscreen mode

Step 9: Start create method in Controller.

//app/Http/Controllers/WebcamController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Storage;
use Illuminate\Support\Str;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Hash;


class WebcamController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index()
    {
        return view('webcam');
    }

    /**
     * Write code on Method
     *
     * @return response()
     */
    public function store(Request $request)
    {
        // Capture and upload image code
        $img = $request->image;
        $folderPath = "public/";
        $image_parts = explode(";base64,", $img);
        $image_type_aux = explode("image/", $image_parts[0]);
        $image_type = $image_type_aux[1];
        $image_base64 = base64_decode($image_parts[1]);
        $rand_code = Str::random(6);
        $fileName = time() . $rand_code . '.png';
        $file = $folderPath . $fileName;

        // Store the file in the public disk
        Storage::disk('public')->put($fileName, $image_base64);
        // Get the public URL of the uploaded file
        $publicUrl = Storage::url($fileName);

        $id = User::create([
            'name'  =>  $request->name,
            'email' =>  $request->email,
            'password' => Hash::make($request->password),
            'photo_name' => $fileName
        ])->id;
        return redirect('photo/'.$id);
    }
    public function photo($id)
    {
        $user = User::where('id',$id)->first();
        return view('photo',compact('user'));
    }

}
Enter fullscreen mode Exit fullscreen mode

Step 10: Create View File

//resources/view/webcam.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>Laravel 12 Webcam Capture Image and Save from Webcam & display with MySQL Database - Chirags.in</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/webcamjs/1.0.25/webcam.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" />
    <style type="text/css">
        #results { padding:20px; border:1px solid; width: 296px; height: 234px;}
    </style>
</head>
<body>

<div class="container">
    <h1 class="text-center">Laravel 12 Webcam Capture Image and Save from Webcam & display with MySQL Database - Chirags.in</h1>

    <form method="POST" action="{{ route('webcam.capture') }}">
        @csrf
        <div class="row">
            <div class="col-md-6">
                <input type="text" name="name" class="form-control" placeholder="Name" /> <br/>
                <input type="text" name="email" class="form-control" placeholder="Email Address" /><br/>
                <input type="password" name="password" class="form-control" placeholder="Password" /><br/>
                <input type="button" class="btn btn-sm btn-primary" id="open_camera" value ="Open Camera"><br/>
                <div id="my_camera" class="d-none"></div>
                <br/>
                <input type=button value="Take Snapshot" onClick="take_snapshot()">
                <input type="hidden" name="image" class="image-tag">
            </div>
            <div class="col-md-6">
                <div id="results"></div>
            </div>
            <div class="col-md-12 text-center">
                <br/>
                <button class="btn btn-success">Submit</button>
            </div>
        </div>
    </form>
</div>

<script language="JavaScript">
    $("#open_camera").click(function() {
        $("#my_camera").removeClass('d-none');
        $("#take_snap").removeClass('d-none');

        Webcam.set({
            width: 250,
            height: 190,
            image_format: 'jpeg',
            jpeg_quality: 90
        });
        Webcam.attach('#my_camera');
    });

    function take_snapshot() {
        Webcam.snap( function(data_uri) {
            $(".image-tag").val(data_uri);
            document.getElementById('results').innerHTML = '<img src="'+data_uri+'"/>';
        } );
    }
</script>

</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Step 11: Create View File for display Photo

//resources/view/photo.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>Laravel 12 Webcam Capture Image and Save from Webcam & display with MySQL Database - Chirags.in</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" />
</head>
<body>

<div class="container">
    <h1 class="text-center">Laravel 12 Webcam Capture Image and Save from Webcam & display with MySQL Database - Chirags.in</h1>
    <picture>
        <img src="{{ asset('storage/' . $user->photo_name) }}" class="img-fluid img-thumbnail" alt="User's image">
    </picture>
</div>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Step 12: Create Storage Link

php artisan storage:link
Step 13: Run Laravel App

php artisan serve
Step 14: Test Application

http://localhost:8000/webcam
For any doubts and query, please write on YouTube video 📽️ comments section.

Note : Flow the Process shown in video 📽️.

😉Subscribe and like for more videos:

https://www.youtube.com/@chiragstutorial

💛Don't forget to, 💘Follow, 💝Like, 💖Share 💙&, Comment

Thanks & Regards,

Chitt Ranjan Mahto "Chirag"

https://www.chirags.in


Note: All scripts used in this demo will be available in our website.

Link will be available in description.

Top comments (1)

Collapse
 
badrul1329 profile image
Mohammad Sohel

Thanks for sharing