gear
Image not found

How to get unique visitor in laravel

Comment (0)

Admin


One way to implement a simple visitor counter in Laravel is to use the Request facade to get the IP address of the visitor and store it in a database table. Here's an example implementation:

Create a new migration to create a visitors table:

 php artisan make:migration create_visitors_table --create=visitors

 

Note: If you want to create Model And migration with same artisan comment follow below command

php artisan make:model Visitor -m

 

In the migration file, define the table schema:

public function up()
{
    Schema::create('visitors', function (Blueprint $table) {
        $table->id();
        $table->string('ip_address')->unique();

        $table->integer('visits')->default(0);
        $table->timestamps();
    });
}
 

 

Run the migration to create the visitors table:

 php artisan migrate

 

In your controller method, use the Request facade to get the visitor's IP address and store it in the visitors table: 

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

public function index(Request $request)
{
    $ip = $request->ip();
    $visitor = Visitor::firstOrCreate(['ip_address' => $ip]);
    $visitor->increment('visits');
    $visitor->save();

    $visitors = Visitor::count();

    return view('welcome', compact('visitors'));
}

 

In your view, display the visitor count:

<p>Visitors: {{ $visitors }}</p>

 

I Hope it will  help................

Thanks


Others Problem Fix Stroy



Comments (0)

Your Comment