Protect Route by User ID

User
How to protect route for particular user id
Assistant
To protect a route for a **particular user ID** in Laravel (e.g., only user with ID `1` can access it), you can use **middleware** or a **route closure check**. Here are both approaches:

### ✅ 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

User
How to protect route for particular user id in vue
Assistant
In a **Vue.js** app (especially with Vue Router), if you want to protect a route for a **specific user ID**, you can do this using **navigation guards**. Here's how you can set it up:

### ✅ 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?

Leave a Comment

Your email address will not be published. Required fields are marked *