170 views
asked in Laravel by
Laravel 11 Webcam Capture Image and Save from Webcam & display with MySQL Database

1 Answer

answered by

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

*********************************************************************************************

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

***********************************************************************************************

YouTube Video:

Step 1: Install Laravel

composer create-project --prefer-dist laravel/laravel laravel_11_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']);

Step 4: Configuration MySQL database in .env file

//.env

DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=laravel_11_webcam
DB_USERNAME=root
DB_PASSWORD=admin@123

Step 5: Create database with the name of laravel_11_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');
    }
}

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',
    ];
     
}

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'));
    }

}

Step 10: Create View File

//resources/view/webcam.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>Laravel 11 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 11 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>

Step 11: Create View File for display Photo

//resources/view/photo.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>Laravel 11 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">LLaravel 11 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>

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

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"

_____________________________________________________________________

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

Link will be available in description.

#chirags 

#chiragstutorial 

#chiragslaraveltutorial

#chiragslaraveltutorials

#laraveltutorial 

#laravel11 

#laravelcourse 

#installlaravel

#laravel_tutorial 

#laravelphp

chirags, chiragstutorial, chiragslaraveltutoria, chiragslaraveltutorial, laraveltutorial, laravel11, laravelcourse, installlarave, laravel_tutorial, laravelphp

Most popular tags

laravel postgresql laravel-10 replication ha postgresql mongodb laravel-11 mongodb database mongodb tutorial ubuntu 24.04 lts streaming-replication mysql database laravel postgresql backup laravel login register logout database mysql php laravel 11 - login with otp valid for 10 minutes. user and admin registration user and admin login multiauth technlogy asp.net asp.net c# mysql master slave replication centos linux laravel sql server schedule backup autobackup postgresql django python haproxy load balancer install self sign ssl laravel 11 gaurds zabbix 7 how to install graylog on ubuntu 24.04 lts | step-by-step asp.net core mvc .net mvc network upload c# ssl integration sql server on ubuntu 22.04 lts mssql server ms sql server sql server user access in postgres mysql password change cent os linux configure replica laravel 11 socialite login with google account google login kubernetes (k8s) install nginx load balancer install install and configure .net 8.0 in ubuntu 24.04 lts php in iis php with iis php tutorial chirags php tutorials chirags php tutorial chirags tutorial laravel 11 guards mongodb sharding metabase business analytics metabase postgresql 16 to postgresql 17 postgresql migration letsencrypt mongodb crud rocky linux laravel custom captcha laravel 11 captcha laravel captcha mongo dll php.ini debian 12 nginx apache nextcloud gitea in ubuntu git gitea npm error node js mysql ndb cluster mysql cluster ssl oracle login register logout in python debian windows shell batch file bat file time stamp date time shopping cart in laravel centos rhel swap memeory rhel 5.5
...