Laravel Api Auth with Vue and Sanctum: All You Need To Know

One of the ways to become a full-stack developer is to adapt Laravel + Vue.js pair. And part of that is authentication. In this tutorial, we will explore how to use Laravel, Vue, and Laravel Sanctum together to build an API authentication, in two ways:

  • In two-in-one Laravel + Vue SPA
  • Or, as separate Vue + API projects

Are you ready? Let's dive in!


Project 1. Laravel SPA: Breeze Vue Example

To have a quick head start, Laravel Breeze starter kit provides a minimal, simple implementation of all Laravel's authentication features. Laravel Breeze also offers Vue scaffolding via an Inertia frontend implementation.

First, create a new Laravel project and install Laravel Breeze:

composer require laravel/breeze --dev

After that execute breeze:install Artisan command with Vue stack and all auth scaffolding will be installed, you should also compile your application's frontend assets:

php artisan breeze:install vue
 
php artisan migrate
npm install
npm run dev

Now you have a full working Single Page Application (SPA). Authentication controllers are placed in the app/Http/Controllers/Auth folder. Let's lookup at the app/Http/Controllers/Auth/AuthenticatedSessionController.php file's store method:

public function store(LoginRequest $request): RedirectResponse
{
$request->authenticate();
 
$request->session()->regenerate();
 
return redirect()->intended(RouteServiceProvider::HOME);
}

This method is called when you log in to your application. As we can see there are no references to tokens. That's right, Vue and Inertia scaffolding uses the laravel_session cookie for authenticated sessions and is handled automatically, so no additional implementation is needed.

Let's move forward with the current setup and create a "protected" demo component that is accessible only to authorized users and displays the currently logged-in user's id and name.

  1. First create a new controller app/Http/Controllers/DemoController.php with the following command.
php artisan:make DemoController

And this is the content of the file:

<?php
 
namespace App\Http\Controllers;
 
use Illuminate\Http\Request;
use Inertia\Inertia;
 
class DemoController extends Controller
{
public function index()
{
return Inertia::render('Demo/Index');
}
}
  1. Add a route to routes/web.php for this controller...

The full tutorial [18 mins, 3510 words] is only for Premium Members

Login Or Become a Premium Member for $129/year or $29/month
What else you will get:
  • 58 courses (1054 lessons, total 46 h 42 min)
  • 78 long-form tutorials (one new every week)
  • access to project repositories
  • access to private Discord

Recent Premium Tutorials