Skip to content

Instantly share code, notes, and snippets.

@marcelozarate
Created October 24, 2021 18:13
Show Gist options
  • Save marcelozarate/7fddedbe938d7b089569391648fc7ec8 to your computer and use it in GitHub Desktop.
Save marcelozarate/7fddedbe938d7b089569391648fc7ec8 to your computer and use it in GitHub Desktop.
Basic Auth Sanctum REST API for Laravel
// routes/api.php
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\AuthController;
Route::post('/register', [AuthController::class, 'register']);
Route::post('/login', [AuthController::class, 'login']);
Route::middleware('auth:sanctum')->get('/whoami', [AuthController::class, 'whoami']);
// app/Http/Controllers/AuthController.php
<?php
namespace App\Http\Controllers;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
class AuthController extends Controller
{
public function register(Request $request) {
$validated = $request->validate([
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:8',
]);
$user = User::create([
'name' => $validated['name'],
'email' => $validated['email'],
'password' => Hash::make($validated['password']),
]);
$token = $user->createToken('auth_token')->plainTextToken;
return response()->json([
'access_token' => $token,
'token_type' => 'Bearer',
]);
}
public function login(Request $request) {
if (!Auth::attempt($request->only('email', 'password'))) {
return response()->json([
'message' => 'Incorrect e-mail or password'
], 401);
}
$user = User::where('email', $request['email'])->firstOrFail();
$token = $user->createToken('auth_token')->plainTextToken;
return response()->json([
'access_token' => $token,
'token_type' => 'Bearer',
]);
}
public function whoami(Request $request) {
return $request->user();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment