Real-Time Score Update
Tahsin Abrar
Posted on August 2, 2024
1. Install Laravel
Create a new Laravel project with:
composer create-project laravel/laravel Laravel-pusher-app
2. Install Pusher
Install the Pusher PHP server library:
composer require pusher/pusher-php-server
3. Set Up Environment
Configure your .env
file with Pusher credentials:
BROADCAST_DRIVER=pusher
PUSHER_APP_ID=your-app-id
PUSHER_APP_KEY=your-app-key
PUSHER_APP_SECRET=your-app-secret
PUSHER_APP_CLUSTER=mt1
Project Files
1. app.blade.php
This is the base Blade template used for rendering other views.
<!DOCTYPE html>
<html lang="en">
<link rel="stylesheet" href="{{ asset('css/app.css') }}">
<body>
@yield('content')
<script src="{{ asset('js/app.js') }}"></script>
<script src="{{ asset('js/pusher.min.js') }}"></script>
<script src="{{ asset('js/jquery.min.js') }}"></script>
<script src="{{ asset('js/axios.min.js') }}"></script>
@yield('script')
</body>
</html>
2. ScoreUpdate.blade.php
Provides the UI for updating the score.
@extends('app')
@section('content')
<div class="container">
<div class="row d-flex justify-content-center">
<div class="p-4 col-md-4">
<div class="card text-center">
<div class="card-body">
<h3>Update Score</h3>
<hr>
<input type="text" class="form-control ScoreValue">
<br>
<button class="btn updateBtn btn-success btn-block">Update</button>
<h4 class="lastScore pt-3"></h4>
</div>
</div>
</div>
</div>
</div>
@endsection
@section('script')
<script>
function updateScore() {
var scoreValue = $('.ScoreValue').val();
var url = "/push-score";
axios.post(url, {
score: scoreValue
}).then(function(response) {
$('.lastScore').html(response.data);
}).catch(function(e) {
console.log(e);
});
}
$('.updateBtn').click(function() {
updateScore();
});
$('.ScoreValue').keypress(function(e) {
if (e.which === 13) {
e.preventDefault();
updateScore();
}
});
</script>
@endsection
3. ScoreBoard.blade.php
Displays the live score using Pusher for real-time updates.
@extends('app')
@section('content')
<div class="container">
<div class="row d-flex justify-content-center">
<div class="p-4 col-md-4">
<div class="card text-center">
<div class="card-body">
<h2 id="score">...</h2>
<h5>Live Score</h5>
</div>
</div>
</div>
</div>
</div>
@endsection
@section('script')
<script>
Pusher = new Pusher('your-app-key', {
cluster: 'mt1',
});
var channel = Pusher.subscribe('my-channel');
channel.bind('my-event', function(data) {
$('#score').html(data['scoreValue']);
});
</script>
@endsection
4. web.php
Defines the routes for displaying views and handling score updates.
<?php
use App\Http\Controllers\ScoreUpdateController;
use Illuminate\Support\Facades\Route;
Route::get('/', function () {
return view('ScoreBoard');
});
Route::get('/update', function () {
return view('ScoreUpdate');
});
Route::post('/push-score', [ScoreUpdateController::class, 'pushScoreValue']);
5. ScoreUpdateController.php
Handles the logic for updating the score and broadcasting the event.
<?php
namespace App\Http\Controllers;
use App\Events\MyEvent;
use Illuminate\Http\Request;
class ScoreUpdateController extends Controller
{
public function pushScoreValue(Request $request){
$score = $request->input('score');
event(new MyEvent($score));
return $score;
}
}
6. MyEvent.php
Event class that broadcasts the score updates to the my-channel
channel.
<?php
namespace App\Events;
use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class MyEvent implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $scoreValue;
public function __construct($scoreValue)
{
$this->scoreValue = $scoreValue;
}
public function broadcastOn(): array
{
return ['my-channel'];
}
public function broadcastAs()
{
return 'my-event';
}
}
Getting Started
-
Configure Environment:
- Copy
.env.example
to.env
and add your Pusher credentials.
- Copy
-
Run Migrations (if any):
php artisan migrate
-
Start the Application:
php artisan serve
-
Start the WebSocket Server (if needed):
npm run dev
Visit http://localhost:8000
to access the application and test real-time score updates.
Posted on August 2, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 30, 2024