Laravel Sanctum, Websockets & Vue [SPA]

Overview

Laravel Auth [SPA]

2021-07-15_22-24-33.mp4
composer require laravel/ui

php artisan ui:auth

Laravel Sanctum

composer require laravel/sanctum

php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"

php artisan migrate

Add Sanctum's middleware to your api middleware group within your app/Http/Kernel.php file:

'api' => [
    \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
    'throttle:60,1',
    \Illuminate\Routing\Middleware\SubstituteBindings::class,
],

.env

...
SESSION_DRIVER=cookie
...
SANCTUM_STATEFUL_DOMAINS=localhost,localhost:8000,localhost:8080,127.0.0.1,127.0.0.1:8000,127.0.0.1:8080,::1
Create a User
php artisan tinker

User::create(['name'=>'John Doe', 'email'=>'[email protected]', 'password'=>Hash::make('secret')]);
Configurations

In routes/api.php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
    return $request->user();
});

In config/cors.php

return [
    'paths' => ['*'],
    'allowed_methods' => ['*'],
    'allowed_origins' => ['*'],
    'allowed_origins_patterns' => [],
    'allowed_headers' => ['*'],
    'exposed_headers' => [],
    'max_age' => 0,
    'supports_credentials' => true,
];

Laravel Websockets

composer require beyondcode/laravel-websockets

php artisan vendor:publish --provider="BeyondCode\LaravelWebSockets\WebSocketsServiceProvider" --tag="migrations"

php artisan migrate

php artisan vendor:publish --provider="BeyondCode\LaravelWebSockets\WebSocketsServiceProvider" --tag="config"

Pusher

composer require pusher/pusher-php-server "~3.0"

.env

BROADCAST_DRIVER=pusher
PUSHER_APP_KEY=s3cr3t
PUSHER_APP_SECRET=s3cr3t
PUSHER_APP_ID=local
PUSHER_APP_CLUSTER=mt1

config/broadcasting.php

'pusher' => [
    'driver' => 'pusher',
    'key' => env('PUSHER_APP_KEY'),
    'secret' => env('PUSHER_APP_SECRET'),
    'app_id' => env('PUSHER_APP_ID'),
    'options' => [
        'cluster' => env('PUSHER_APP_CLUSTER'),
        'encrypted' => true,
        'host' => '127.0.0.1',
        'port' => 6001,
        'scheme' => 'http'
    ],
],

config/app.php uncomment

App\Providers\BroadcastServiceProvider::class

Dashboard

http://127.0.0.1:8000/laravel-websockets

Event & Channel

php artisan make:event Chat
class Chat implements ShouldBroadcast{

public $payload = 'Hello World!';
...
public function broadcastOn()
    {
        return new PrivateChannel('App.User.1');
    }
    
public function broadcastAs()
    {
        return 'new-message-event';
    }
...
}

In routes/channels.php

Broadcast::channel('App.User.{id}', function ($user, $id) {
    //Check User's Authorization to listen on the channel.
    return true;
}

Authorizing Private Broadcast Channels

You should place the Broadcast::routes method call within your routes/api.php file:

Broadcast::routes(['middleware' => ['auth:sanctum']]);

Running Laravel & Websocket Server

php artisan serve
php artisan websockets:serve

UI

npm i laravel-echo pusher-js axios
<script>
import axios from "axios";
import Pusher from "pusher-js";
import Echo from "laravel-echo";

console.log(Pusher);

export default {
  name: "App",

  data() {
    return {
      data: {
        email: "[email protected]",
        password: "secret",
      },
    };
  },

  async mounted() {
    axios.defaults.withCredentials = true;

    await axios.get("http://localhost:8000/sanctum/csrf-cookie");

    await axios.post("http://localhost:8000/login", this.data);

    const { data } = await axios.get("http://localhost:8000/api/user");

    let echo = new Echo({
      broadcaster: "pusher",
      key: "s3cr3t",
      wsHost: "localhost",
      wsPort: 6001,
      forceTLS: false,
      cluster: "mt1",
      disableStats: true,
      authorizer: (channel, options) => {
        console.log(options);
        return {
          authorize: (socketId, callback) => {
            axios({
              method: "POST",
              url: "http://localhost:8000/api/broadcasting/auth",
              data: {
                socket_id: socketId,
                channel_name: channel.name,
              },
            })
              .then((response) => {
                callback(false, response.data);
              })
              .catch((error) => {
                callback(true, error);
              });
          },
        };
      },
    });

    echo
      .private(`App.Models.User.${data.id}`)
      .listen(".new-message-event", (message) => {
        console.log(message);
      });
  },
};
</script>

Fire an Event

php artisan tinker
event(new App\Events\Chat())
You might also like...
Awes.io // boilerplate based on Vue, Nuxt, TailwindCSS plus Laravel as a backend. 🤟
Awes.io // boilerplate based on Vue, Nuxt, TailwindCSS plus Laravel as a backend. 🤟

Platform for Interactive Business Applications 10x faster to create than the traditional way • 3x increase application experiences • 60% decrease in d

MediaDB is a web-based media streaming service written in Laravel and Vue.

MediaDB (API) MediaDB is a web-based media streaming service written in Laravel and Vue. The nginx-vod-module is used for on-the-fly repackaging of MP

Rebuild the todo website with Laravel and Vue
Rebuild the todo website with Laravel and Vue

Lara-Todo This is a course that I took at Udmey, to create a todo website with Laravel and Vue.js Start First we need to download and setup Composer.

Reactive Form Builder for Vue.js with Laravel Support
Reactive Form Builder for Vue.js with Laravel Support

Dynamic Form Builder for Laravel with Vue.js Create even the most complex forms with ease, using two-sided validation, eloquent, nested elements, cond

A Laravel UI preset for UIkit and Vue.js

New version: torrix/laravel-uikit This package is for Laravel 6, and is no longer maintained. Please use the Laravel 8 version UIkit frontend UI prese

Projeto em Laravel para práticar redis, cache e vue js

About Laravel Laravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable and creative experie

An application with Laravel, Vue, Redis and Mysql

p align="center"a href="https://laravel.com" target="_blank"img src="https://raw.githubusercontent.com/laravel/art/master/logo-lockup/5%20SVG/2%2

Vueform Laravel + Vue 3 + TailwindCSS 3 Boilerplate
Vueform Laravel + Vue 3 + TailwindCSS 3 Boilerplate

Vueform Laravel + Vue 3 + TailwindCSS 3 Boilerplate Last tested with Laravel 8.75. Installation Clone this repo with: git clone https://github.com/vue

This template should help get you started developing with laravel 9 + Vue 3 in Vite + Tailwind

simple-project This template should help get you started developing with laravel 9 + Vue 3 in Vite + Tailwind

Owner
Kritish Dhaubanjar
Kritish Dhaubanjar
Websockets-Client (Sample) laravel

About Laravel Laravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable and creative experie

Filimantaptius Gulo 1 Mar 8, 2022
Master Websockets Laravel

About Laravel Laravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable and creative experie

Filimantaptius Gulo 1 Mar 8, 2022
Websockets for Laravel. Done right.

Bring the power of WebSockets to your Laravel application. Drop-in Pusher replacement, SSL support, Laravel Echo support and a debug dashboard are just some of its features.

Beyond Code 4.6k Jan 6, 2023
Laravel Sanctum support for Laravel Lighthouse

Lighthouse Sanctum Add Laravel Sanctum support to Lighthouse Requirements Installation Usage Login Logout Register Email Verification Forgot Password

Daniël de Wit 43 Dec 21, 2022
Tiny hands is a Laravel multi-tenant boilerplate with SPA and i18n.

About Tiny Hands Tiny hands is a Laravel multi-tenant boilerplate with SPA and i18n using the following technology stack: Backend Laravel 8.0 API with

Bertrand Kintanar 12 Jun 23, 2022
REST API with auth using Laravel 8 and Sanctum

Laravel REST API with Sanctum This is an example of a REST API using auth tokens with Laravel Sanctum Usage Change the .env.example to .env and add yo

Brad Traversy 251 Dec 29, 2022
A Laravel 8 Project Implement with GraphQL With Sanctum APIs Authentications Which utilized in Any Frontend or Any Mobile Application Programs.

A Laravel 8 Project Implement with GraphQL With Sanctum APIs Authentications Which utilized in Any Frontend or Any Mobile Application Programs.

Vikas Ukani 3 Jan 6, 2022
API para Autenticación desarrollada con Laravel 8 y Sanctum

About Laravel Laravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable and creative experie

Informática DP 3 Dec 9, 2021
Load head metadata from a manifest file which can be shared with a SPA project

Laravel Head Manifest Installation Step 1: Add Laravel Head Manifest to your laravel project composer require critiq/laravel-head-manifest Step 2: Add

Critiq 1 Nov 17, 2021
An open source Laravel Soundboard with Admin Panel CRUD (Create Read Update Delete) built on Laravel, Bootstrap, and Vue.js

Laravel Soundboard An open source Laravel Soundboard with Admin Panel CRUD (Create Read Update Delete) built on Laravel 5.8, Bootstrap 4, Vue.js, Boot

Jeremy Kenedy 24 Oct 28, 2022