Real-time Kabar karo Laravel lan Redis

Real-time kabar minangka fitur umum ing aplikasi web kanggo menehi tandha cepet lan nganyari kanggo pangguna tanpa perlu refresh kaca. Ing Laravel, sampeyan bisa kanthi gampang nggabungake Redis kanggo ngleksanakake real-time kabar kanthi efisien. Redis bakal digunakake minangka antrian kanggo ngirim kabar saka server menyang klien langsung.

Nginstal Redis lan Laravel

Kanggo miwiti, instal Redis ing server lan instal predis/predis paket kasebut Laravel liwat Composer.

composer require predis/predis

Real-time Notifikasi Integrasi

Konfigurasi Antrian ing Laravel

Pisanan, atur antrian Laravel kanthi nambahake Redis informasi menyang .env file kasebut.

QUEUE_CONNECTION=redis  
REDIS_HOST=127.0.0.1  
REDIS_PASSWORD=null  
REDIS_PORT=6379  

Nggawe an Event

Nggawe event in Laravel kanggo ngirim real-time kabar.

php artisan make:event NewNotificationEvent

Banjur, mbukak app/Events/NewNotificationEvent.php file lan ngatur event isi.

use Illuminate\Broadcasting\Channel;  
use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow;  
use Illuminate\Queue\SerializesModels;  
  
class NewNotificationEvent implements ShouldBroadcastNow  
{  
    use SerializesModels;  
  
    public $message;  
  
    public function __construct($message)  
    {  
        $this->message = $message;  
    }  
  
    public function broadcastOn()  
    {  
        return new Channel('notifications');  
    }  
}  

Ngatur Broadcast Driver

Bukak config/broadcasting.php file lan gunakake redis driver kanggo ngleksanakake real-time kabar nganggo Redis.

'connections' => [  
    'redis' => [  
        'driver' => 'redis',  
        'connection' => 'default',  
    ],  
    // ...  
],  

Kirimi Real-time Notifikasi

Yen sampeyan kudu ngirim real-time kabar, gunakake sing event mung digawe ing controller utawa panyedhiya layanan.

use App\Events\NewNotificationEvent;  
  
public function sendNotification()  
{  
    $message = 'You have a new notification!';  
    event(new NewNotificationEvent($message));  
}  

Nangani Real-time Notifikasi ing Klien

Pungkasan, nangani real-time kabar ing klien nggunakake JavaScript lan Laravel Echo. Priksa manawa sampeyan wis nginstal lan ngatur Laravel Echo kanggo aplikasi sampeyan.

// Connect to the 'notifications' channel  
const channel = Echo.channel('notifications');  
  
// Handle the event when receiving a real-time notification  
channel.listen('.NewNotificationEvent',(notification) => {  
    alert(notification.message);  
});  

 

Kesimpulan

Nggabungake Redis lan Laravel ngidini sampeyan masang real-time kabar kanthi gampang ing aplikasi web sampeyan. Yen ana kabar anyar, aplikasi bakal dikirim liwat Redis, lan klien bakal nampa kabar langsung tanpa perlu refresh kaca. Iki nambah pengalaman pangguna lan nambah interaktivitas aplikasi.