In this lesson, let's work on the logout functionality. I will show you how to use Inertia to make a link, but with post method.
To perform the logout, first on the back-end, let's create the route.
routes/web.php:
Route::view('/', 'dashboard')->name('dashboard'); Route::middleware('auth')->group(function () { Route::resource('posts', PostController::class); Route::inertia('about', 'About')->name('about'); Route::post('logout', [\App\Http\Controllers\Auth\LoginController::class, 'destroy'])->name('logout'); });Route::inertia('login', 'Auth/Login')->name('login');Route::post('login', [\App\Http\Controllers\Auth\LoginController::class, 'store'])->name('login.post');
In the Controller, we will use the logic from Laravel Breeze again.
app/Http/Controllers/Auth/LoginController.php:
use Illuminate\Http\Request;use Illuminate\Support\Facades\Auth; class LoginController extends Controller{ // ... public function destroy(Request $request): RedirectResponse { Auth::guard('web')->logout(); $request->session()->invalidate(); $request->session()->regenerateToken(); return redirect()->route('login'); }}
Next, the logout button must be changed to Link. And Inertia allows to set the method for the link.
resources/views/js/Layouts/AppLayout.jsx:
import { useState, useEffect } from 'react';import { Link, usePage } from '@inertiajs/react'; export default function AppLayout({ children }) { const { flash } = usePage().props; return ( // ... <div className="flex items-center"> <button className="ml-4 inline-flex items-center rounded-mdborder border-transparent bg-gray-800 px-4 py-2 text-xs font-semibold uppercase tracking-widest text-white transition duration-150 ease-in-out hover:bg-gray-700 focus:shadow-outline-gray focus:border-gray-900 focus:outline-none active:bg-gray-900"> <Link href={route('logout')} method="post" className="ml-4 inline-flex items-center rounded-mdborder border-transparent bg-gray-800 px-4 py-2 text-xs font-semibold uppercase tracking-widest text-white transition duration-150 ease-in-out hover:bg-gray-700 focus:shadow-outline-gray focus:border-gray-900 focus:outline-none active:bg-gray-900"> Log out </button> </Link> </div> // ... );}
After pressing the logout button now we are logged out of the application and cannot access the protected routes.
In this short lesson, I wanted to show that you can provide a method to the Inertia link.