Protect Route by User ID
March 23, 2025 · AI Conversations
—
### ✅ Option 1: **Middleware Approach (Recommended for Reusability)**
#### 1. Create a custom middleware:
php artisan make:middleware CheckUserId
#### 2. In `app/Http/Middleware/CheckUserId.php`:
public function handle($request, Closure $next)
{
// Only allow user with ID 1
if (auth()->check() && auth()->id() == 1) {
return $next($request);
}
abort(403, 'Unauthorized');
}
#### 3. Register middleware in `app/Http/Kernel.php`:
“`php
protected $routeMiddleware = [
// …
'checkUserId' => AppHttpMiddleware
—
### ✅ Assumptions
– You are using Vue Router.
– You have access to the current authenticated user’s ID (maybe from Vuex, Pinia, or an API call).
– You want to allow a route only if `user.id === 1`.
—
### 🔐 Option 1: Global Navigation Guard
// router/index.js or router.js
import { useAuthStore } from '@/stores/auth' // or wherever you store user info
router.beforeEach((to, from, next) => {
const auth = useAuthStore(); // or use your logic to get the user
if (to.meta.requiresSpecificUser && auth.user?.id !== 1) {
// redirect or block access
return next({ name: 'Forbidden' }) // or redirect to home/login
}
next();
})
Then in your route:
{
path: '/admin-only',
name: 'AdminOnly',
component: () => import('@/views/AdminOnly.vue'),
meta: {
requiresSpecificUser: true
}
}
—
### 🔐 Option 2: Per-Route Guard (Inline)
{
path: '/admin-only',
name: 'AdminOnly',
component: () => import('@/views/AdminOnly.vue'),
beforeEnter: (to, from, next) => {
const user = JSON.parse(localStorage.getItem('user')) // or use a store
if (user?.id === 1) {
next()
} else {
next({ name: 'Forbidden' })
}
}
}
—
### ✅ Bonus: Redirect to a Forbidden Page
Add a simple `Forbidden.vue` component and route:
{
path: '/forbidden',
name: 'Forbidden',
component: () => import('@/views/Forbidden.vue')
}
—
Would you like help integrating this with Inertia or Pinia if you’re using those?