How to Broadcast events with Laravel Echo and Vuejs Part 1
In today's tutorial, we are going to see how to broadcast an event with Laravel Echo and Vuejs 3.
We will create an app where the user can create an account and log in and once he is logged in an event will be broadcasted to other users showing a notification that the user x has logged in and the same thing when he logout.
Create the event
I assume that you have already a new fresh Laravel app and you have already created a database with the migrations we need only one table which is users.
Next, let's add a new event:
php artisan make:event UserSessionChanged
the event has a message and a type which is the alert type success or danger.
<?php
namespace App\Events;
use Illuminate\Support\Facades\Log;
use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
class UserSessionChanged implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $message;
public $type;
/**
* Create a new event instance.
*
* @return void
*/
public function __construct($message, $type)
{
//
$this->message = $message;
$this->type = $type;
}
/**
* Get the channels the event should broadcast on.
*
* @return \Illuminate\Broadcasting\Channel|array
*/
public function broadcastOn()
{
return new PrivateChannel('notifications');
}
}
Create the UserController
Next, we add a new controller UserController here we have all the methods that we need, inside auth, we broadcast the event once the user has logged in, and the same thing in the logout method.
<?php
namespace App\Http\Controllers;
use App\Events\UserSessionChanged;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
class UserController extends Controller
{
//
public function registerForm(){
if(auth()->check()){
return redirect('/');
}
return view('auth.register');
}
public function loginForm(){
if(auth()->check()){
return redirect('/');
}
return view('auth.login');
}
public function store(Request $request){
$this->validate($request, [
'name' => 'required',
'email' => 'required',
'password' => 'required'
]);
$user = User::create([
'name' => $request->name,
'email' => $request->email,
'password' => Hash::make($request->password)
]);
auth()->login($user);
return redirect('/');
}
public function auth(Request $request){
if(auth()->attempt([
'email' => $request->email,
'password' => $request->password,
])){
$user = User::whereEmail($request->email)->first();
broadcast(new UserSessionChanged("$user->name has logged in", "alert-success"));
return redirect('/');
}else{
return redirect('/login')->with([
'error' => 'These credentials do not match any of our records.'
]);
}
}
public function logout(){
$username = auth()->user()->name;
auth()->logout();
broadcast(new UserSessionChanged("$username has logged out", "alert-danger"));
return redirect('/');
}
}
Create the app.blade.php file
Inside views, the structure of our files will be like this:
> views
> auth
login.blade.php
register.blade.php
> layouts
app.blade.php
navbar.blade.php
home.blade.php
The content of the file app.blade.php:
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<title>Laravel Realtime</title>
</head>
<body>
@include('layouts.navbar')
<div class="container" id="app">
@yield('content')
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
@vite('resources/js/app.js')
</body>
</html>
Create the navbar.blade.php
The content of the file navbar.blade.php:
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<div class="container-fluid">
<a class="navbar-brand" href="{{url('/')}}">Laravel Realtime</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav me-auto mb-2 mb-lg-0">
<li class="nav-item">
<a class="nav-link active" aria-current="page" href="{{url('/')}}">Home</a>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">
Account
</a>
<ul class="dropdown-menu" aria-labelledby="navbarDropdown">
@guest
<li><a class="dropdown-item" href="{{route('register')}}">Register</a></li>
<li><a class="dropdown-item" href="{{route('login')}}">Login</a></li>
@endguest
<li><hr class="dropdown-divider"></li>
@auth
<li><a class="dropdown-item" href="#">{{auth()->user()->name}}</a></li>
<li><a class="dropdown-item"
onclick="document.getElementById('logoutForm').submit();"
href="#">Logout</a></li>
<form id="logoutForm" action="{{route('logout')}}" method="post">
@csrf
</form>
@endauth
</ul>
</li>
</ul>
</div>
</div>
</nav>
Create the register.blade.php
The content of the file register.blade.php:
@extends('layouts.app')
@section('content')
<div class="container">
<div class="row justify-content-center my-5">
<div class="col-md-8">
<div class="card">
<div class="card-header">{{ __('Register') }}</div>
<div class="card-body">
<form method="POST" action="{{ route('register') }}">
@csrf
<div class="row mb-3">
<label for="name" class="col-md-4 col-form-label text-md-end">{{ __('Name') }}</label>
<div class="col-md-6">
<input id="name" type="text" class="form-control @error('name') is-invalid @enderror" name="name" value="{{ old('name') }}" required autocomplete="name" autofocus>
@error('name')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
@enderror
</div>
</div>
<div class="row mb-3">
<label for="email" class="col-md-4 col-form-label text-md-end">{{ __('Email Address') }}</label>
<div class="col-md-6">
<input id="email" type="email" class="form-control @error('email') is-invalid @enderror" name="email" value="{{ old('email') }}" required autocomplete="email">
@error('email')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
@enderror
</div>
</div>
<div class="row mb-3">
<label for="password" class="col-md-4 col-form-label text-md-end">{{ __('Password') }}</label>
<div class="col-md-6">
<input id="password" type="password" class="form-control @error('password') is-invalid @enderror" name="password" required autocomplete="new-password">
@error('password')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
@enderror
</div>
</div>
<div class="row mb-0">
<div class="col-md-6 offset-md-4">
<button type="submit" class="btn btn-primary">
{{ __('Register') }}
</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
@endsection