### Environment Configuration - Copy .env.example Source: https://github.com/yudayahya/laravel-inertia-react-shadcn-spatie/blob/main/README.md Copies the example environment file to .env, which will contain your application's configuration settings. You will need to customize this file after copying. ```bash cp .env.example .env ``` -------------------------------- ### Install Dependencies - Composer and NPM Source: https://github.com/yudayahya/laravel-inertia-react-shadcn-spatie/blob/main/README.md Installs project dependencies using Composer for PHP and NPM for Node.js packages. This ensures all necessary libraries are available for the project. ```bash composer install npm install ``` -------------------------------- ### Making Inertia Requests from React Components Source: https://context7.com/yudayahya/laravel-inertia-react-shadcn-spatie/llms.txt Illustrates how to initiate navigation and data requests from React components using Inertia's `router`. It covers GET requests for page visits and POST requests for sending data to the server. Ensure `@inertiajs/react` is installed. ```javascript import { router } from '@inertiajs/react'; // GET request: router.visit('/users'); // POST request with data: router.post('/users', { name: 'John Doe', email: 'john@example.com' }); ``` -------------------------------- ### Render React Components with Inertia in Laravel Controller Source: https://context7.com/yudayahya/laravel-inertia-react-shadcn-spatie/llms.txt Demonstrates how to render a React component from a Laravel controller using Inertia.js. This method passes data to the React component, enabling full-stack development without a separate API. It requires the `inertia` package to be installed. ```php use Inertia\Inertia; public function index() { return Inertia::render('Dashboard', [ 'users' => User::all(), 'stats' => [ 'total' => User::count(), 'active' => User::where('active', true)->count(), ] ]); } ``` -------------------------------- ### Clone Repository - Git Source: https://github.com/yudayahya/laravel-inertia-react-shadcn-spatie/blob/main/README.md Clones the starter kit repository from GitHub to your local machine. This is the first step in setting up the project. ```bash git clone https://github.com/yudayahya/laravel-inertia-react-shadcn-spatie.git ``` -------------------------------- ### Build Frontend Bundle - NPM Source: https://github.com/yudayahya/laravel-inertia-react-shadcn-spatie/blob/main/README.md Builds the frontend assets (JavaScript, CSS) for production using NPM scripts. This command compiles and optimizes your frontend code. ```bash npm run build ``` -------------------------------- ### User Registration API Source: https://context7.com/yudayahya/laravel-inertia-react-shadcn-spatie/llms.txt Allows new users to register an account by providing their name, email, and password. Includes validation for uniqueness and password confirmation. ```APIDOC ## POST /register ### Description Register a new user account with name, email, and password validation including email uniqueness checks and password confirmation. ### Method POST ### Endpoint /register ### Parameters #### Request Body - **name** (string) - Required - The name of the user. - **email** (string) - Required - The email address of the user. Must be unique. - **password** (string) - Required - The user's password. - **password_confirmation** (string) - Required - The user's password confirmation. ### Request Example ```json { "name": "John Doe", "email": "john@example.com", "password": "SecurePassword123", "password_confirmation": "SecurePassword123" } ``` ### Response #### Success Response (200) Redirects to `/dashboard` after successful registration. #### Error Response (422) ```json { "message": "The email has already been taken.", "errors": { "email": [ "The email has already been taken." ] } } ``` ``` -------------------------------- ### Database Seeding - Artisan Source: https://github.com/yudayahya/laravel-inertia-react-shadcn-spatie/blob/main/README.md Populates the database with initial data using seeders. This is often used for setting up default users, roles, or other necessary records. ```bash php artisan db:seed ``` -------------------------------- ### Database Migration - Artisan Source: https://github.com/yudayahya/laravel-inertia-react-shadcn-spatie/blob/main/README.md Runs database migrations to set up the necessary tables in your database. This command is part of the Laravel Artisan command-line interface. ```bash php artisan migrate ``` -------------------------------- ### User Login API Source: https://context7.com/yudayahya/laravel-inertia-react-shadcn-spatie/llms.txt Authenticates existing users using their email and password. Implements rate limiting to prevent brute-force attacks. ```APIDOC ## POST /login ### Description Authenticate users with email and password, including rate limiting (5 attempts) and session management. ### Method POST ### Endpoint /login ### Parameters #### Request Body - **email** (string) - Required - The user's email address. - **password** (string) - Required - The user's password. - **remember** (boolean) - Optional - Whether to remember the user's session. ### Request Example ```json { "email": "john@example.com", "password": "SecurePassword123", "remember": true } ``` ### Response #### Success Response (200) Redirects to `/dashboard` with a valid session cookie. #### Error Response (422) ```json { "message": "These credentials do not match our records.", "errors": { "email": [ "These credentials do not match our records." ] } } ``` #### Rate Limit Error (429) ```json { "message": "Too many login attempts. Please try again in X seconds." } ``` ``` -------------------------------- ### Profile Management API Source: https://context7.com/yudayahya/laravel-inertia-react-shadcn-spatie/llms.txt Endpoints for viewing, updating, and deleting user profile information. ```APIDOC ## Profile View ### Description Retrieves the user's profile edit page. ### Method GET ### Endpoint `/profile` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) Inertia rendered profile edit page. #### Response Example None (Renders a view). --- ## Profile Update ### Description Updates user profile information including name and email. Email changes trigger a verification reset. ### Method PATCH ### Endpoint `/profile` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **name** (string) - Optional - The user's new name. - **email** (string) - Optional - The user's new email address. ### Request Example ```json { "name": "Jane Doe", "email": "jane@example.com" } ``` ### Response #### Success Response (200) Redirects to the profile edit page. #### Response Example None (Redirects to a page). --- ## Account Deletion ### Description Deletes the user's account after verifying the current password. ### Method DELETE ### Endpoint `/profile` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **password** (string) - Required - The current password for account verification. ### Request Example ```json { "password": "CurrentPassword123" } ``` ### Response #### Success Response (200) Logs out the user, deletes the account, invalidates the session, and redirects to the homepage. #### Response Example None (Redirects to the homepage). #### Error Response - **message** (string) - Error message indicating incorrect password. - **errors** (object) - Contains validation errors, specifically for the password field. ```json { "message": "The password is incorrect.", "errors": { "password": [ "The password is incorrect." ] } } ``` ``` -------------------------------- ### Initialize Database with Roles and Permissions (PHP) Source: https://context7.com/yudayahya/laravel-inertia-react-shadcn-spatie/llms.txt These seeders initialize the database with default roles ('super-admin', 'admin'), a comprehensive set of permissions, and a super admin user. The `RoleSeeder` creates roles, `PermissionSeeder` assigns permissions to the 'super-admin' role, and `SuperAdminSeeder` creates the super admin user and assigns the 'super-admin' role. Run with `php artisan db:seed`. ```php // Seeder: database/seeders/RoleSeeder.php use Spatie\Permission\Models\Role; public function run(): void { $roles = ['super-admin', 'admin']; foreach ($roles as $role) { Role::findOrCreate($role); } } // Seeder: database/seeders/PermissionSeeder.php use Spatie\Permission\Models\Permission; public function run(): void { $permissions = [ 'create user', 'read user', 'update user', 'delete user', 'create admin', 'read admin', 'update admin', 'delete admin', 'create role', 'read role', 'update role', 'delete role', 'create permission', 'read permission', 'update permission', 'delete permission', ]; foreach ($permissions as $permission) { $createdPermission = Permission::findOrCreate($permission); $createdPermission->assignRole('super-admin'); } } // Seeder: database/seeders/SuperAdminSeeder.php use App\Models\User; public function run(): void { $superAdmin = User::firstOrCreate([ 'name' => 'Super Admin', 'email' => 'superadmin@email.com' ],[ 'password' => bcrypt('superadmin'), ]); $superAdmin->assignRole('super-admin'); } // Running seeders: php artisan db:seed // Or run specific seeder: php artisan db:seed --class=SuperAdminSeeder // Result: Creates roles (super-admin, admin), 16 permissions, and super admin user // Login credentials: superadmin@email.com / superadmin ``` -------------------------------- ### Spatie Roles and Permissions API Source: https://context7.com/yudayahya/laravel-inertia-react-shadcn-spatie/llms.txt APIs for managing user roles and permissions using Spatie's Laravel Permission package. ```APIDOC ## Spatie Roles and Permissions Management ### Description This section details how to assign, check, and manage roles and permissions for users using the Spatie Laravel Permission package. ### Methods #### Assigning Roles to Users - **`assignRole(string|array $roles)`**: Assigns one or more roles to the user. - Example: `$user->assignRole('admin');` - Example: `$user->assignRole(['editor', 'contributor']);` #### Checking User Roles - **`hasRole(string|array $roles)`**: Checks if the user has a specific role or any of the specified roles. - Example: `if ($user->hasRole('super-admin')) { ... }` - **`hasAnyRole(string|array $roles)`**: Checks if the user has at least one of the specified roles. - Example: `if ($user->hasAnyRole(['admin', 'editor'])) { ... }` - **`hasAllRoles(string|array $roles)`**: Checks if the user has all of the specified roles. - Example: `if ($user->hasAllRoles(['admin', 'editor'])) { ... }` #### Assigning Permissions to Users - **`givePermissionTo(string|array $permissions)`**: Grants one or more permissions directly to the user. - Example: `$user->givePermissionTo('edit articles');` - Example: `$user->givePermissionTo(['create posts', 'delete posts']);` #### Checking User Permissions - **`can(string $permission)`**: Checks if the user has a specific permission (can also be used with middleware). - Example: `if ($user->can('edit articles')) { ... }` - **`hasPermissionTo(string $permission)`**: An alternative method to check for a specific permission. - Example: `if ($user->hasPermissionTo('delete articles')) { ... }` #### Assigning Permissions to Roles - **`Role::findByName('role_name')->givePermissionTo(string|array $permissions)`**: Assigns permissions to a specific role. - Example: `$role = Role::findByName('admin'); $role->givePermissionTo('manage users');` ### Middleware Usage Routes can be protected using role and permission middleware. #### Role Middleware ```php Route::middleware(['auth', 'role:super-admin'])->group(function () { // Routes accessible only by super-admins }); ``` #### Permission Middleware ```php Route::middleware(['auth', 'permission:create articles'])->group(function () { // Routes accessible only by users with 'create articles' permission }); ``` ### Models and Traits - **User Model**: Must use the `Spatie\Permission\Traits\HasRoles` trait. ```php use Spatie\Permission\Traits\HasRoles; class User extends Authenticatable { use HasApiTokens, HasFactory, Notifiable, HasRoles; // ... } ``` - **Permission Model**: `Spatie\Permission\Models\Permission` - **Role Model**: `Spatie\Permission\Models\Role` ``` -------------------------------- ### Spatie Roles and Permissions Management - Laravel Source: https://context7.com/yudayahya/laravel-inertia-react-shadcn-spatie/llms.txt Demonstrates how to implement role-based access control (RBAC) using Spatie's Laravel Permission package. This includes assigning roles and permissions to users, checking their access rights, assigning permissions to roles, and using middleware for route protection. ```php // User model with HasRoles trait: // app/Models/User.php use Spatie\Permission\Traits\HasRoles; class User extends Authenticatable { use HasApiTokens, HasFactory, Notifiable, HasRoles; protected $fillable = ['name', 'email', 'password']; } // Assigning roles: use App\Models\User; $user = User::find(1); $user->assignRole('super-admin'); $user->assignRole(['admin', 'editor']); // Multiple roles // Checking roles: if ($user->hasRole('super-admin')) { // User has super-admin role } if ($user->hasAnyRole(['admin', 'super-admin'])) { // User has at least one of these roles } if ($user->hasAllRoles(['admin', 'editor'])) { // User has all specified roles } // Assigning permissions: use Spatie\Permission\Models\Permission; $permission = Permission::create(['name' => 'create user']); $user->givePermissionTo('create user'); $user->givePermissionTo(['read user', 'update user', 'delete user']); // Checking permissions: if ($user->can('create user')) { // User has permission } if ($user->hasPermissionTo('update user')) { // Alternative permission check } // Assigning permissions to roles: use Spatie\Permission\Models\Role; $role = Role::findByName('admin'); $role->givePermissionTo(['create user', 'read user', 'update user', 'delete user']); // Middleware usage in routes: Route::middleware(['auth', 'role:super-admin'])->group(function () { // Routes only accessible to super-admin }); Route::middleware(['auth', 'permission:create user'])->group(function () { // Routes only accessible with specific permission }); ``` -------------------------------- ### User Login with Rate Limiting (PHP) Source: https://context7.com/yudayahya/laravel-inertia-react-shadcn-spatie/llms.txt Authenticates users using their email and password. It enforces rate limiting to prevent brute-force attacks, allowing only 5 attempts within a certain period. Successful authentication establishes a user session, while failed attempts trigger appropriate error messages and rate limiting warnings. ```php public function authenticate(): void { $this->ensureIsNotRateLimited(); if (! Auth::attempt($this->only('email', 'password'), $this->boolean('remember'))) { RateLimiter::hit($this->throttleKey()); throw ValidationException::withMessages([ 'email' => trans('auth.failed'), ]); } RateLimiter::clear($this->throttleKey()); } ``` ```php public function ensureIsNotRateLimited(): void { if (! RateLimiter::tooManyAttempts($this->throttleKey(), 5)) { return; } $seconds = RateLimiter::availableIn($this->throttleKey()); throw ValidationException::withMessages([ 'email' => trans('auth.throttle', [ 'seconds' => $seconds, 'minutes' => ceil($seconds / 60), ]), ]); } ``` -------------------------------- ### Password Reset API Source: https://context7.com/yudayahya/laravel-inertia-react-shadcn-spatie/llms.txt Endpoints for requesting a password reset link and submitting the reset form. ```APIDOC ## Password Reset Request ### Description Request a password reset link via email for forgotten passwords with rate limiting. ### Method GET ### Endpoint `/forgot-password` ### Parameters #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) Displays the password reset request form. #### Response Example None --- ## Password Reset Submission ### Description Submits the password reset form with the provided token, email, and new password. ### Method POST ### Endpoint `/forgot-password` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **email** (string) - Required - The email address for the password reset. ### Request Example ```json { "email": "john@example.com" } ``` ### Response #### Success Response (200) Redirects with a status message indicating the reset link has been sent. #### Response Example None (Redirects to a page with a status message). --- ## Reset Password Form Display ### Description Displays the password reset form pre-filled with a token and email. ### Method GET ### Endpoint `/reset-password/{token}` ### Parameters #### Path Parameters - **token** (string) - Required - The password reset token. #### Query Parameters - **email** (string) - Required - The email address associated with the token. #### Request Body None ### Request Example None ### Response #### Success Response (200) Displays the password reset form. #### Response Example None --- ## Reset Password Submission ### Description Submits the new password for the reset process. ### Method POST ### Endpoint `/reset-password` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **token** (string) - Required - The password reset token received via email. - **email** (string) - Required - The email address associated with the account. - **password** (string) - Required - The new password for the account. - **password_confirmation** (string) - Required - The confirmation of the new password. ### Request Example ```json { "token": "reset_token_from_email", "email": "john@example.com", "password": "NewSecurePassword123", "password_confirmation": "NewSecurePassword123" } ``` ### Response #### Success Response (200) Redirects to a page with a success status message upon successful password reset. #### Response Example None (Redirects to a page with a success message). #### Error Response Returns validation errors if the provided information is incorrect or passwords do not match. ``` -------------------------------- ### Form Submission with Inertia's useForm Hook Source: https://context7.com/yudayahya/laravel-inertia-react-shadcn-spatie/llms.txt Demonstrates how to handle form submissions in React using Inertia's `useForm` hook. This hook manages form state, submission status, and errors, integrating seamlessly with Inertia's routing for data persistence and validation feedback. Requires `@inertiajs/react`. ```typescript import { useForm } from '@inertiajs/react'; const { data, setData, post, processing, errors } = useForm({ name: '', email: '', password: '', }); const submit = (e: React.FormEvent) => { e.preventDefault(); post('/register'); }; return (
); ``` -------------------------------- ### User Registration with Validation (PHP) Source: https://context7.com/yudayahya/laravel-inertia-react-shadcn-spatie/llms.txt Handles the registration of new users in Laravel. It validates user input including name, email uniqueness, and password confirmation. Upon successful validation, it creates a new user, dispatches a registered event, logs the user in, and redirects them to the home page. Error responses are returned with a 422 status code. ```php public function store(Request $request): RedirectResponse { $request->validate([ 'name' => 'required|string|max:255', 'email' => 'required|string|lowercase|email|max:255|unique:'.User::class, 'password' => ['required', 'confirmed', RulesPassword::defaults()], ]); $user = User::create([ 'name' => $request->name, 'email' => $request->email, 'password' => Hash::make($request->password), ]); event(new Registered($user)); Auth::login($user); return redirect(RouteServiceProvider::HOME); } ``` -------------------------------- ### Sharing Global Data via Inertia Middleware in Laravel Source: https://context7.com/yudayahya/laravel-inertia-react-shadcn-spatie/llms.txt Explains how to share data globally across all Inertia pages in a Laravel application using middleware. This is useful for providing authentication status, flash messages, or other consistently needed information to the frontend. The `HandleInertiaRequests` middleware is typically used. ```php // app/Http/Middleware/HandleInertiaRequests.php public function share(Request $request): array { return array_merge(parent::share($request), [ 'auth' => [ 'user' => $request->user(), ], 'flash' => [ 'message' => fn () => $request->session()->get('message') ], ]); } ``` -------------------------------- ### Implement Sanctum API Authentication (PHP) Source: https://context7.com/yudayahya/laravel-inertia-react-shadcn-spatie/llms.txt This section details how to secure API routes using Laravel Sanctum for stateless authentication via tokens. It shows how to protect routes, generate API tokens for users, make authenticated API requests using `curl`, and manage token abilities (scopes) and revocation. Rate limiting for API routes is also configured. ```php // API route protected with Sanctum: routes/api.php use Illuminate\Http\Request; Route::middleware('auth:sanctum')->get('/user', function (Request $request) { return $request->user(); }); // Creating API tokens: use Laravel\Sanctum\HasApiTokens; // User model already includes HasApiTokens trait class User extends Authenticatable { use HasApiTokens, HasFactory, Notifiable, HasRoles; } // Generate token for user: $user = User::find(1); $token = $user->createToken('api-token')->plainTextToken; // API request with token: curl -X GET https://example.com/api/user \ -H "Authorization: Bearer {token}" \ -H "Accept: application/json" // Response: { "id": 1, "name": "John Doe", "email": "john@example.com", "email_verified_at": "2024-01-01T00:00:00.000000Z", "created_at": "2024-01-01T00:00:00.000000Z", "updated_at": "2024-01-01T00:00:00.000000Z" } // Token abilities/scopes: $token = $user->createToken('api-token', ['user:read', 'user:update'])->plainTextToken; // Checking token abilities in controller: if ($request->user()->tokenCan('user:update')) { // User can update } // Revoking tokens: $user->tokens()->delete(); // Revoke all tokens $user->currentAccessToken()->delete(); // Revoke current token // Rate limiting configured in app/Providers/RouteServiceProvider.php: RateLimiter::for('api', function (Request $request) { return Limit::perMinute(60)->by($request->user()?->id ?: $request->ip()); }); ``` -------------------------------- ### User Logout API Source: https://context7.com/yudayahya/laravel-inertia-react-shadcn-spatie/llms.txt Logs out the currently authenticated user by terminating their session. ```APIDOC ## POST /logout ### Description Terminate authenticated session, invalidate session data, and regenerate CSRF token for security. ### Method POST ### Endpoint /logout ### Parameters Requires: Authentication middleware ### Response #### Success Response (200) Redirects to the homepage (`/`) with an invalidated session. ``` -------------------------------- ### React Component for Inertia Page with Props Source: https://context7.com/yudayahya/laravel-inertia-react-shadcn-spatie/llms.txt Shows a basic React component designed to receive props from Inertia.js. It utilizes `@inertiajs/react` for data fetching and rendering. The component expects specific props like `users` and `stats`, and uses `Head` for setting the page title. ```typescript import { Head } from '@inertiajs/react'; interface Props { users: Array<{id: number; name: string; email: string}>; stats: {total: number; active: number}; } export default function Dashboard({ users, stats }: Props) { return ( <>