Overview
TheFileController provides file serving functionality with advanced authorization, supporting both owner access and role-based viewing permissions.
Namespace: App\Http\Controllers
Class: FileController
Methods
show()
Retrieves and serves an attachment file with role-based authorization checks. Route:GET /attachment/{id}
Route Name: attachment.show
Middleware: auth, verified
Authentication: Required
Description
This method serves attachment files with flexible authorization:- File owners can always access their attachments
- Users with special viewing permissions (e.g., doctors, admins) can access patient files
- Returns the file with appropriate headers for browser display
canView() method on the User model to determine if a user has permission to view another user’s attachments.
Request Parameters
| Parameter | Type | Location | Required | Description |
|---|---|---|---|---|
| id | integer | Route | Yes | Attachment ID |
Response
Success (200): File content with appropriate MIME type and headers Forbidden (403): User does not have permission to view the file- Message: “No tienes permiso para ver este archivo.”
Code Example
HTTP Request Example
Usage in Blade
Authorization Logic
The authorization follows this flow:Error Responses
Comparison with AttachmentController
| Feature | FileController | AttachmentController |
|---|---|---|
| Route binding | Manual ID lookup | Model binding |
| Authorization | Owner + role-based | Owner only |
| Response type | Storage::response() | response()->file() |
| Use case | Shared/viewable files | Strictly private files |
Security
- Uses
findOrFail()to validate attachment existence - Owner verification for basic access control
- Role-based permission checking via
canView()method - File existence validation prevents path traversal
- Stored files served through Laravel’s storage facade
Dependencies
App\Models\AttachmentIlluminate\Support\Facades\Storage- User model must implement
canView()method
