Overview
The ShareData component allows users to share their health data with other users by granting viewer access. It provides username search functionality, viewer management, and validation to ensure proper access control.Class Information
Namespace:App\Livewire\Profile
Class: ShareData
Public Properties
| Property | Type | Description |
|---|---|---|
username | string | Username of the user to grant access to |
search | string | Search query for finding users |
searchResults | array | Collection of users matching the search query |
Methods
updatedSearch()
Automatically triggered when the search property is updated. Performs a live search for users.- Requires minimum 2 characters to start searching
- Excludes the current authenticated user from results
- Returns maximum 5 matching users
- Uses LIKE query for partial matching
selectUser($username)
Selects a user from the search results and populates the username field. Parameters:$username(string) - Username of the selected user
addViewer()
Validates and grants viewer access to the specified user.- Username must exist in the database
- User cannot grant access to themselves
- User cannot grant duplicate access
- Creates a relationship in the
allowedViewers()pivot table - Flashes a success message to the session
- Resets the username field
removeViewer($id)
Revokes viewer access for a specific user. Parameters:$id(int) - User ID of the viewer to remove
Validation Rules
addViewer()
| Field | Rules | Custom Messages |
|---|---|---|
username | required, exists:users,username | exists: “No encontramos ningún usuario con ese Nick.” |
Custom Validation Errors
| Condition | Error Message |
|---|---|
| User tries to share with themselves | ”No puedes compartirte datos a ti mismo.” |
| User already has access | ”Este usuario ya tiene acceso a tus datos.” |
Render Data
Therender() method provides the following data to the view:
| Variable | Type | Description |
|---|---|---|
viewers | Collection | List of users who have viewer access |
Component Usage
Basic Implementation
Complete Blade Template Example
With Loading States
Database Relationships
This component relies on the following relationship defined in the User model:user_id- The user who owns the dataviewer_id- The user who has viewer access
Security Considerations
- Self-sharing prevention: Users cannot grant access to themselves
- Duplicate prevention: The same user cannot be added multiple times
- User isolation: Search results exclude the authenticated user
- Authorization: Only the authenticated user can manage their own viewers
Dependencies
App\Models\User- User model with allowedViewers relationshipIlluminate\Validation\ValidationException- For custom validation errors
