### Flarum REST API Request Examples (Bash) Source: https://context7.com/flarum/framework/llms.txt Provides command-line examples using cURL to interact with the Flarum REST API. These examples cover authentication, creating discussions, filtering and sorting discussions, updating posts, deleting discussions, retrieving user data, marking notifications, and updating settings. Requires appropriate API credentials and endpoints. ```bash # Authenticate and get token curl -X POST https://forum.example.com/api/token \ -H "Content-Type: application/json" \ -d '{ "identification": "username", "password": "password" }' # Response # { # "token": "abc123xyz...", # "userId": "1" # } # Create a discussion curl -X POST https://forum.example.com/api/discussions \ -H "Content-Type: application/json" \ -H "Authorization: Token abc123xyz..." \ -d '{ "data": { "type": "discussions", "attributes": { "title": "My New Discussion", "content": "This is the first post content" }, "relationships": { "tags": { "data": [ {"type": "tags", "id": "1"}, {"type": "tags", "id": "3"} ] } } } }' # Get discussions with filters and includes curl "https://forum.example.com/api/discussions?filter[q]=search+term&include=user,tags,firstPost&sort=-createdAt&page[limit]=20" \ -H "Authorization: Token abc123xyz..." # Update a post curl -X PATCH https://forum.example.com/api/posts/42 \ -H "Content-Type: application/json" \ -H "Authorization: Token abc123xyz..." \ -d '{ "data": { "type": "posts", "id": "42", "attributes": { "content": "Updated post content" } } }' # Delete a discussion curl -X DELETE https://forum.example.com/api/discussions/10 \ -H "Authorization: Token abc123xyz..." # Get current user curl https://forum.example.com/api/users/1 \ -H "Authorization: Token abc123xyz..." # Mark all notifications as read curl -X POST https://forum.example.com/api/notifications/read \ -H "Authorization: Token abc123xyz..." # Update settings (admin only) curl -X POST https://forum.example.com/api/settings \ -H "Content-Type: application/json" \ -H "Authorization: Token abc123xyz..." \ -d '{ "forum_title": "My Forum", "welcome_message": "Welcome to our community!", "default_locale": "en" }' ``` -------------------------------- ### Install Flarum Typescript Config (npm) Source: https://github.com/flarum/framework/blob/2.x/js-packages/tsconfig/README.md Installs the 'flarum-tsconfig' package as a development dependency using npm. ```properties npm install --save-dev flarum-tsconfig ``` -------------------------------- ### Install Prettier Config with npm and yarn Source: https://github.com/flarum/framework/blob/2.x/js-packages/prettier-config/README.md Installs the Flarum Prettier configuration as a development dependency using either npm or yarn package managers. This is the first step to integrating the configuration into a project. ```bash npm i -D @flarum/prettier-config ``` ```bash yarn add -D @flarum/prettier-config ``` -------------------------------- ### Install Flarum Typescript Config (yarn) Source: https://github.com/flarum/framework/blob/2.x/js-packages/tsconfig/README.md Installs the 'flarum-tsconfig' package as a development dependency using yarn. ```properties yarn add --dev flarum-tsconfig ``` -------------------------------- ### Create Custom API Endpoints in PHP for Flarum Source: https://context7.com/flarum/framework/llms.txt Defines custom API endpoints for Flarum resources, enabling functionality beyond standard CRUD operations. This example demonstrates adding 'avatar.upload' and 'sendConfirmation' endpoints to a UserResource. It requires Flarum's API and Bus components. ```php use Flarum\Api\Context; use Flarum\Api\Endpoint\Endpoint; use Flarum\Api\Resource\AbstractResource; use Flarum\Api\Schema; use Flarum\Bus\Dispatcher; class UserResource extends AbstractResource { public function endpoints(): array { return [ // Standard endpoints Endpoint\Create::make(), Endpoint\Update::make(), Endpoint\Delete::make(), Endpoint\Show::make(), Endpoint\Index::make(), // Custom endpoint: Upload avatar Endpoint\Endpoint::make('avatar.upload') ->route('POST', '/{id}/avatar') ->authenticated() ->visible(fn (Context $context) => $context->getActor()->can('uploadAvatar', $context->model) ) ->action(function (Context $context) { $file = Arr::get($context->request->getUploadedFiles(), 'avatar'); if (!$file || $file->getError() !== UPLOAD_ERR_OK) { throw new \InvalidArgumentException('Invalid avatar file'); } $bus = resolve(Dispatcher::class); return $bus->dispatch( new UploadAvatar( (int) $context->modelId, $file, $context->getActor() ) ); }), // Custom endpoint: Send confirmation email Endpoint\Endpoint::make('sendConfirmation') ->route('POST', '/{id}/send-confirmation') ->authenticated() ->action(function (Context $context) { $user = $context->model; $actor = $context->getActor(); if ($user->is_email_confirmed) { throw new \Exception('Email already confirmed'); } if ($actor->id !== $user->id && !$actor->isAdmin()) { throw new \Exception('Permission denied'); } $token = EmailToken::generate($user->email, $user->id); $token->save(); Mail::to($user->email)->send(new ConfirmationEmail($token)); return $user; }) ->response(function (Context $context, User $user) { return new JsonResponse(['success' => true], 200); }) ]; } } ``` -------------------------------- ### Manage Flarum Discussions with PHP API Source: https://context7.com/flarum/framework/llms.txt This snippet demonstrates how to create, update, hide, restore, and query discussions using the Flarum Discussion API in PHP. It includes examples of eager loading relationships and accessing discussion properties. ```php use Flarum\Discussion\Discussion; use Flarum\Post\Post; use Flarum\User\User; // Create a discussion with first post $actor = User::find(1); $discussion = Discussion::start('My Discussion Title', $actor); // Add content via first post $post = Post::reply( $discussion->id, 'This is the content of my first post.', $actor->id, null ); $discussion->setFirstPost($post); $discussion->save(); // Update discussion $discussion->rename('Updated Title'); $discussion->save(); // Hide/restore discussion $discussion->hide($actor); $discussion->restore(); // Query discussions with eager loading $discussions = Discussion::query() ->whereVisibleTo($actor) ->with(['user', 'lastPostedUser', 'firstPost', 'tags']) ->orderBy('last_posted_at', 'desc') ->paginate(20); // Access discussion properties echo $discussion->title; // "My Discussion Title" echo $discussion->slug; // "my-discussion-title" echo $discussion->comment_count; // 15 echo $discussion->participant_count; // 5 echo $discussion->created_at->format('Y-m-d'); // "2025-01-15" // Access relationships $firstPost = $discussion->firstPost; $lastPost = $discussion->lastPost; $author = $discussion->user; $posts = $discussion->posts()->get(); ``` -------------------------------- ### Get Discussions Source: https://context7.com/flarum/framework/llms.txt Retrieves a list of discussions with options for filtering, sorting, including related data, and pagination. ```APIDOC ## GET /api/discussions ### Description Retrieves a list of discussions. Supports filtering, sorting, including related resources, and pagination. ### Method GET ### Endpoint /api/discussions #### Query Parameters - **filter[q]** (string) - Optional - Search term for discussions. - **include** (string) - Optional - Comma-separated list of related resources to include (e.g., 'user,tags,firstPost'). - **sort** (string) - Optional - Field to sort by, prefixed with '-' for descending order (e.g., '-createdAt'). - **page[limit]** (integer) - Optional - Maximum number of discussions to return per page. ### Request Example ```bash curl "https://forum.example.com/api/discussions?filter[q]=search+term&include=user,tags,firstPost&sort=-createdAt&page[limit]=20" \ -H "Authorization: Token YOUR_API_TOKEN" ``` ``` -------------------------------- ### Get User Source: https://context7.com/flarum/framework/llms.txt Retrieves the details of a specific user. ```APIDOC ## GET /api/users/{id} ### Description Retrieves the profile information for a specific user. ### Method GET ### Endpoint /api/users/{id} #### Path Parameters - **id** (integer) - Required - The ID of the user to retrieve. ### Request Example ```bash curl https://forum.example.com/api/users/1 \ -H "Authorization: Token YOUR_API_TOKEN" ``` ``` -------------------------------- ### PHP Authorization Policies for Flarum Discussions Source: https://context7.com/flarum/framework/llms.txt Defines authorization policies for discussion-related actions in Flarum. It includes checks for user permissions and specific conditions like ownership and time limits. Usage examples demonstrate how to check and assert abilities. ```php use Flarum\User\User; use Flarum\Discussion\Discussion; use Flarum\User\Access\AbstractPolicy; class DiscussionPolicy extends AbstractPolicy { // Generic ability check using permissions public function can(User $actor, string $ability): ?string { if ($actor->hasPermission('discussion.'.$ability)) { return $this->allow(); } return null; } // Specific ability: rename discussion public function rename(User $actor, Discussion $discussion): ?string { // Author can rename their own discussion if ($discussion->user_id == $actor->id && $actor->can('reply', $discussion)) { $settings = resolve('flarum.settings'); $allowRenaming = $settings->get('allow_renaming'); // Check time limit if ($allowRenaming === '-1' || ($allowRenaming === 'reply' && $discussion->participant_count <= 1) || (is_numeric($allowRenaming) && $discussion->created_at->diffInMinutes(null, true) < $allowRenaming)) { return $this->allow(); } } return null; } // Specific ability: hide discussion public function hide(User $actor, Discussion $discussion): ?string { if ($discussion->user_id == $actor->id && $discussion->participant_count <= 1 && $actor->can('reply', $discussion)) { return $this->allow(); } return null; } // Force allow (bypasses other checks) public function delete(User $actor, Discussion $discussion): ?string { if ($actor->hasPermission('discussion.deletePermanently')) { return $this->forceAllow(); } return null; } } // Usage in code $actor = User::find(1); $discussion = Discussion::find(1); if ($actor->can('rename', $discussion)) { $discussion->rename('New Title'); $discussion->save(); } // Assert ability (throws exception if fails) $actor->assertCan('delete', $discussion); $discussion->delete(); ``` -------------------------------- ### Flarum Application Bootstrap and Container (PHP) Source: https://context7.com/flarum/framework/llms.txt Demonstrates how to create a Flarum application instance and resolve services from its container, which extends Laravel's. It shows how to access database, cache, and event services, as well as retrieve application configuration and version. ```php use Flarum\Foundation\Application; use Flarum\Foundation\Paths; // Create application instance $paths = new Paths([ 'base' => __DIR__, 'public' => __DIR__.'/public', 'storage' => __DIR__.'/storage', ]); $app = new Application($paths); // Resolve services from container $db = $app->make('db'); $cache = $app->make('cache'); $events = $app->make('events'); // Get application config $forumUrl = $app->url(); // Get base forum URL $apiUrl = $app->url('api'); // Get API URL $debug = $app->config('debug', false); // Check version $version = $app->version(); // Returns "2.0.0-beta.3" ``` -------------------------------- ### PHP Flarum Event System Dispatch and Listen Source: https://context7.com/flarum/framework/llms.txt Demonstrates how to dispatch and listen to domain events in Flarum using PHP. Includes defining custom events, dispatching them, and setting up listeners and subscribers to react to these events for various functionalities. ```php use Flarum\Discussion\Discussion; use Flarum\Discussion\Event\Started; use Flarum\Post\Event\Posted; use Flarum\User\User; use Illuminate\Contracts\Events\Dispatcher; // Define an event class DiscussionWasTagged { public function __construct( public Discussion $discussion, public User $actor, public array $oldTags, public array $newTags ) {} } // Dispatch events $events = resolve(Dispatcher::class); $events->dispatch(new Started($discussion, $actor)); $events->dispatch(new DiscussionWasTagged($discussion, $actor, [], $newTags)); // Listen to events in extender (new Extend\Event()) ->listen(Started::class, function (Started $event) { $discussion = $event->discussion; $actor = $event->actor; // Send notification to moderators $moderators = User::query() ->whereHas('groups', fn ($q) => $q->where('id', 4)) ->get(); foreach ($moderators as $moderator) { $moderator->notify(new NewDiscussionNotification($discussion)); } }) ->listen(Posted::class, PostListener::class); // Event subscriber (groups related listeners) class TagSubscriber { public function subscribe(Dispatcher $events): void { $events->listen( DiscussionWasTagged::class, self::class.'@updateMetadata' ); $events->listen( Discussion\Event\Deleted::class, self::class.'@decrementCounts' ); } public function updateMetadata(DiscussionWasTagged $event): void { // Update tag post counts and last discussion } public function decrementCounts(Discussion\Event\Deleted $event): void { // Decrement tag discussion counts } } (new Extend\Event())->subscribe(TagSubscriber::class); ``` -------------------------------- ### Flarum Helper Functions for Service Resolution (PHP) Source: https://context7.com/flarum/framework/llms.txt Illustrates the use of global helper functions in Flarum for convenient access to container services, configuration values, event dispatching, and path manipulation. These functions simplify common tasks like resolving repositories, retrieving settings, and triggering events. ```php // Resolve any service from the container $db = resolve('db'); $userRepository = resolve(Flarum\User\UserRepository::class); // Resolve with parameters $user = resolve(Flarum\User\User::class, ['attributes' => ['username' => 'john']]); // Get configuration values $siteName = config('flarum.forum_title'); $defaultLocale = config('flarum.default_locale', 'en'); // Dispatch events event(new Flarum\Discussion\Event\Started($discussion)); event(Flarum\User\Event\Saving::class, [$user, $actor, $data]); // Get path helpers $basePath = base_path('config.php'); $publicPath = public_path('assets'); $storagePath = storage_path('logs'); ``` -------------------------------- ### PHP: Flarum Extender Configuration for Frontend, API, Models, and Events Source: https://context7.com/flarum/framework/llms.txt This PHP code demonstrates a typical Flarum extender configuration. It shows how to add frontend JavaScript and CSS, define API routes, establish model relationships, listen to events, and register authorization policies. This is a core pattern for customizing Flarum's behavior. ```php use Flarum\Extend; use Flarum\Api\Resource; use Flarum\Api\Endpoint; use Flarum\Api\Schema; use Flarum\Discussion\Discussion; use Flarum\Post\Post; use Flarum\User\User; return [ // Add frontend JavaScript and CSS (new Extend\Frontend('forum')) ->js(__DIR__.'/js/dist/forum.js') ->css(__DIR__.'/less/forum.less') ->route('/custom/{id}', 'custom.page', CustomPage::class), // Register API routes (new Extend\Routes('api')) ->post('/custom/action', 'custom.action', CustomController::class) ->get('/custom/{id}', 'custom.show', CustomController::class) ->delete('/custom/{id}', 'custom.delete', CustomController::class), // Add model relationships (new Extend\Model(Discussion::class)) ->belongsToMany('tags', Tag::class, 'discussion_tag') ->hasMany('customRelation', CustomModel::class), (new Extend\Model(Post::class)) ->belongsToMany('likes', User::class, 'post_likes', 'post_id', 'user_id'), // Extend existing API resources with new fields (new Extend\ApiResource(Resource\DiscussionResource::class)) ->fields(fn () => [ Schema\Boolean::make('isLiked') ->get(fn (Discussion $discussion, Context $context) => $discussion->likes()->where('user_id', $context->getActor()->id)->exists() ), Schema\Integer::make('likeCount') ->get(fn (Discussion $discussion) => $discussion->likes()->count()), Schema\Relationship\ToMany::make('tags') ->includable() ]) ->endpoint(Endpoint\Index::class, function (Endpoint\Index $endpoint) { return $endpoint ->addDefaultInclude(['tags', 'user']) ->eagerLoad('likes'); }), // Listen to events (new Extend\Event()) ->listen(Discussion\Event\Started::class, Listener\NotifyModerators::class) ->listen(Post\Event\Posted::class, function ($event) { // Inline listener Log::info('Post created: '.$event->post->id); }) ->subscribe(Listener\SubscriberClass::class), // Register authorization policies (new Extend\Policy()) ->modelPolicy(Discussion::class, Access\DiscussionPolicy::class) ->globalPolicy(Access\GlobalPolicy::class), // Control model visibility (new Extend\ModelVisibility(Discussion::class)) ->scopeAll(function (User $actor, Builder $query) { if (!$actor->hasPermission('viewPrivateDiscussions')) { $query->where('is_private', false); } }), // Add settings (new Extend\Settings()) ->serializeToForum('customSetting', 'extension.custom_setting') ->default('extension.default_value', 'value'), // Register notifications (new Extend\Notification()) ->type(CustomNotification::class, ['alert', 'email']) ]; ``` -------------------------------- ### Settings Extension Source: https://context7.com/flarum/framework/llms.txt Manages application settings, including serialization to the frontend and default values. ```APIDOC ## Settings Extension ### Description Configures application settings, making them available on the frontend and setting default values. ### Method `ExtendSettings` ### Endpoint N/A (Settings configuration) ### Parameters N/A ### Request Example ```php (new Extend\Settings()) ->serializeToForum('customSetting', 'extension.custom_setting') ->default('extension.default_value', 'value') ``` ### Response N/A ``` -------------------------------- ### Create Discussion Source: https://context7.com/flarum/framework/llms.txt Creates a new discussion with a title, content, and optional tags. ```APIDOC ## POST /api/discussions ### Description Creates a new discussion thread in the forum. ### Method POST ### Endpoint /api/discussions #### Request Body - **data** (object) - Required - The discussion payload. - **type** (string) - Required - Must be 'discussions'. - **attributes** (object) - Required - Discussion attributes. - **title** (string) - Required - The title of the discussion. - **content** (string) - Required - The first post content of the discussion. - **relationships** (object) - Optional - Relationships to other resources. - **tags** (object) - Optional - An array of tag objects to associate with the discussion. - **data** (array) - Array of tag objects, each with 'type' and 'id'. ### Request Example ```bash curl -X POST https://forum.example.com/api/discussions \ -H "Content-Type: application/json" \ -H "Authorization: Token YOUR_API_TOKEN" \ -d '{ "data": { "type": "discussions", "attributes": { "title": "My New Discussion", "content": "This is the first post content" }, "relationships": { "tags": { "data": [ {"type": "tags", "id": "1"}, {"type": "tags", "id": "3"} ] } } } }' ``` ``` -------------------------------- ### Frontend Extension Source: https://context7.com/flarum/framework/llms.txt Defines JavaScript and CSS assets for the forum frontend and registers custom routes. ```APIDOC ## Frontend Extension ### Description Adds JavaScript and CSS files to the forum frontend and registers custom routes. ### Method `ExtendFrontend` ### Endpoint N/A (Configuration for frontend assets and routes) ### Parameters N/A ### Request Example ```php (new Extend\Frontend('forum')) ->js(__DIR__.'/js/dist/forum.js') ->css(__DIR__.'/less/forum.less') ->route('/custom/{id}', 'custom.page', CustomPage::class) ``` ### Response N/A ``` -------------------------------- ### Flarum Eloquent ORM Database Queries (PHP) Source: https://context7.com/flarum/framework/llms.txt Demonstrates how to perform various database operations using Flarum's Eloquent ORM. This includes basic queries with filtering and ordering, complex queries involving relationships and conditional logic, aggregations, joins for related data, and using scopes for visibility filtering. It also shows how to create, update, and eagerly load relationships to prevent N+1 query problems. ```php use Flarum\Discussion\Discussion; use Flarum\Post\Post; use Flarum\User\User; use Illuminate\Database\Eloquent\Builder; // Basic queries $users = User::query() ->where('is_email_confirmed', true) ->where('created_at', '>', now()->subDays(7)) ->orderBy('discussion_count', 'desc') ->limit(10) ->get(); // Complex queries with relationships $discussions = Discussion::query() ->whereVisibleTo($actor) ->with(['user', 'firstPost', 'tags']) ->whereHas('tags', function (Builder $query) { $query->where('slug', 'general'); }) ->where(function (Builder $query) { $query->where('is_private', false) ->orWhere('user_id', $this->actor->id); }) ->orderBy('last_posted_at', 'desc') ->paginate(20); // Aggregations $userStats = User::query() ->selectRaw('COUNT(*) as total_users') ->selectRaw('SUM(discussion_count) as total_discussions') ->selectRaw('AVG(comment_count) as avg_comments') ->first(); // Joins $topPosters = User::query() ->join('posts', 'users.id', '=', 'posts.user_id') ->where('posts.created_at', '>', now()->subMonth()) ->groupBy('users.id') ->selectRaw('users.*, COUNT(posts.id) as posts_count') ->orderByRaw('posts_count DESC') ->limit(10) ->get(); // Scopes (visibility filtering) $visibleDiscussions = Discussion::query() ->whereVisibleTo($actor) ->get(); // Create with relationships $discussion = Discussion::create([ 'title' => 'New Discussion', 'user_id' => $actor->id, ]); $discussion->tags()->attach([1, 2, 3]); $post = Post::create([ 'discussion_id' => $discussion->id, 'user_id' => $actor->id, 'type' => 'comment', 'content' => 'Content here', ]); // Update relationships $discussion->tags()->sync([1, 4, 5]); $user->groups()->attach(3); $user->groups()->detach(2); // Eager loading to prevent N+1 queries $discussions = Discussion::with([ 'user', 'firstPost.user', 'lastPost', 'tags' => function ($query) { $query->orderBy('position'); }, 'posts' => function ($query) { $query->where('is_private', false) ->orderBy('created_at', 'asc'); } ])->paginate(20); ``` -------------------------------- ### Flarum User Resource API (PHP) Source: https://context7.com/flarum/framework/llms.txt Details the Flarum API for managing users, including CRUD operations, schema definition with validation rules, and authorization checks. It demonstrates creating users, defining resource attributes like username and email, handling passwords, and interacting with the User model for operations and relationship retrieval. ```php use Flarum\Api\Context; use Flarum\Api\Endpoint; use Flarum\Api\Resource\UserResource; use Flarum\Api\Schema; use Flarum\User\User; // Create a new user $endpoint = Endpoint\Create::make() ->visible(function (Context $context) { $settings = resolve('flarum.settings'); if (!$settings->get('allow_sign_up')) { return $context->getActor()->isAdmin(); } return true; }); // Define user schema with validation Schema\Str::make('username') ->requiredOnCreateWithout(['token']) ->unique('users', 'username', true) ->regex('/^(?![0-9]*$)[a-z0-9_-]+$/i') ->minLength(3) ->maxLength(30) ->writable(function (User $user, Context $context) { return $context->creating() || $context->getActor()->can('editCredentials', $user); }); Schema\Str::make('email') ->requiredOnCreateWithout(['token']) ->email(['filter']) ->unique('users', 'email', true); Schema\Str::make('password') ->minLength(8) ->visible(false); // User model usage $user = User::find(1); $user->rename('newusername'); $user->changeEmail('new@email.com'); $user->changePassword('newpassword123'); $user->activate(); $user->save(); // Check permissions if ($user->hasPermission('discussion.startDiscussion')) { // User can start discussions } if ($user->can('edit', $post)) { // User can edit this specific post } // User relationships $discussions = $user->discussions()->get(); $posts = $user->posts()->get(); $groups = $user->groups()->get(); $notifications = $user->notifications()->unread()->get(); ``` -------------------------------- ### Event Listener Extension Source: https://context7.com/flarum/framework/llms.txt Registers listeners for Flarum events and subscribes to event providers. ```APIDOC ## Event Listener Extension ### Description Allows custom logic to be executed when specific Flarum events are triggered. ### Method `ExtendEvent` ### Endpoint N/A (Event-driven) ### Parameters N/A ### Request Example ```php (new Extend\Event()) ->listen(Discussion\Event\Started::class, Listener\NotifyModerators::class) ->listen(Post\Event\Posted::class, function ($event) { // Inline listener Log::info('Post created: '.$event->post->id); }) ->subscribe(Listener\SubscriberClass::class) ``` ### Response N/A ``` -------------------------------- ### Jest Configuration for Flarum Extensions (CJS) Source: https://github.com/flarum/framework/blob/2.x/js-packages/jest-config/README.md This code snippet sets up the Jest configuration for Flarum extensions by importing and executing the @flarum/jest-config package. It requires the 'jest.config.cjs' file to be present in the project. ```javascript module.exports = require('@flarum/jest-config')(); ``` -------------------------------- ### Configure Prettier in package.json Source: https://github.com/flarum/framework/blob/2.x/js-packages/prettier-config/README.md Specifies the Flarum Prettier configuration to be used by the Prettier tool within a project's package.json file. This tells Prettier to load and apply the shared Flarum formatting rules. ```json // package.json { "name": "my-cool-package", "version": "1.0.0", "prettier": "@flarum/prettier-config" // ... } ``` -------------------------------- ### Policy Extension Source: https://context7.com/flarum/framework/llms.txt Registers authorization policies for models and globally. ```APIDOC ## Policy Extension ### Description Defines authorization rules to control access to specific actions and resources. ### Method `ExtendPolicy` ### Endpoint N/A (Authorization configuration) ### Parameters N/A ### Request Example ```php (new Extend\Policy()) ->modelPolicy(Discussion::class, Access\DiscussionPolicy::class) ->globalPolicy(Access\GlobalPolicy::class) ``` ### Response N/A ``` -------------------------------- ### API Routes Extension Source: https://context7.com/flarum/framework/llms.txt Registers custom API endpoints for the Flarum API. ```APIDOC ## API Routes Extension ### Description Registers custom API endpoints, allowing for custom actions and data retrieval. ### Method `ExtendRoutes('api')` ### Endpoint Configurable via the `ExtendRoutes` class. ### Parameters N/A ### Request Example ```php (new Extend\Routes('api')) ->post('/custom/action', 'custom.action', CustomController::class) ->get('/custom/{id}', 'custom.show', CustomController::class) ->delete('/custom/{id}', 'custom.delete', CustomController::class) ``` ### Response N/A ``` -------------------------------- ### Configure tsconfig.json for Flarum Extensions Source: https://github.com/flarum/framework/blob/2.x/js-packages/tsconfig/README.md Provides a baseline tsconfig.json configuration for Flarum extensions, extending the 'flarum-tsconfig' package. It specifies files to include and compiler options for outputting typings and path mappings. ```jsonc { // Use Flarum's tsconfig as a starting point "extends": "flarum-tsconfig", // This will match all .ts, .tsx, .d.ts, .js, .jsx files in your `src` folder // and also tells your Typescript server to read core's global typings for // access to `dayjs` and `$` in the global namespace. "include": ["src/**/*", "../vendor/flarum/core/js/dist-typings/@types/**/*"], "compilerOptions": { // This will output typings to `dist-typings` "declarationDir": "./dist-typings", "paths": { "flarum/*": ["../vendor/flarum/core/js/dist-typings/*"] } } } ``` -------------------------------- ### Manage Flarum Posts with PHP API Source: https://context7.com/flarum/framework/llms.txt This snippet illustrates how to create, edit, hide, restore, and query posts within a discussion using the Flarum Post API in PHP. It covers formatting post content, accessing metadata, and navigating relationships. ```php use Flarum\Post\Post; use Flarum\Post\CommentPost; use Flarum\Discussion\Discussion; use Flarum\User\User; // Create a post $post = CommentPost::reply( $discussionId = 1, $content = 'This is my post content.', $userId = 1, $ipAddress = '127.0.0.1' ); $post->save(); // Edit post content $post->revise('Updated content', $actor); $post->save(); // Hide/restore post $post->hide($actor); $post->restore(); // Query posts with filtering $posts = Post::query() ->whereVisibleTo($actor) ->where('discussion_id', 1) ->where('type', 'comment') ->orderBy('created_at', 'asc') ->get(); // Format post content to HTML $html = $post->formatContent($request); // Access post metadata echo $post->number; // Post number in discussion (1, 2, 3...) echo $post->created_at->diffForHumans(); // "2 hours ago" echo $post->edited_at; // null or Carbon instance echo $post->ip_address; // "127.0.0.1" // Relationships $discussion = $post->discussion; $user = $post->user; $editedBy = $post->editedUser; ``` -------------------------------- ### Basic Webpack Configuration for Flarum Source: https://github.com/flarum/framework/blob/2.x/js-packages/webpack-config/README.md Imports the Flarum Webpack configuration and exports it. Custom options can be merged using webpack-merge. ```javascript var config = require('flarum-webpack-config'); module.exports = config(options); ``` -------------------------------- ### User Authentication Source: https://context7.com/flarum/framework/llms.txt Authenticates a user using their username/email and password to obtain an API token. ```APIDOC ## POST /api/token ### Description Authenticates a user and returns an API token for subsequent requests. ### Method POST ### Endpoint /api/token #### Request Body - **identification** (string) - Required - The user's username or email address. - **password** (string) - Required - The user's password. ### Request Example ```bash curl -X POST https://forum.example.com/api/token \ -H "Content-Type: application/json" \ -d '{ "identification": "username", "password": "password" }' ``` ### Response #### Success Response (200) Returns the API token and the user ID. - **token** (string) - The authentication token. - **userId** (string) - The ID of the authenticated user. #### Response Example ```json { "token": "abc123xyz...", "userId": "1" } ``` ``` -------------------------------- ### Webpack Bundle Analyzer Script Source: https://github.com/flarum/framework/blob/2.x/js-packages/webpack-config/README.md Adds a script to package.json to build the project with the Webpack Bundle Analyzer enabled. This helps visualize the JS bundle. ```json { "analyze": "npx cross-env ANALYZER=true npm run build" } ``` -------------------------------- ### Model Extension Source: https://context7.com/flarum/framework/llms.txt Adds relationships to existing Flarum models. ```APIDOC ## Model Extension ### Description Extends Flarum models by adding new relationships, allowing for more complex data structures. ### Method `ExtendModel` ### Endpoint N/A (Configuration for model relationships) ### Parameters N/A ### Request Example ```php (new Extend\Model(Discussion::class)) ->belongsToMany('tags', Tag::class, 'discussion_tag') ->hasMany('customRelation', CustomModel::class) (new Extend\Model(Post::class)) ->belongsToMany('likes', User::class, 'post_likes', 'post_id', 'user_id') ``` ### Response N/A ``` -------------------------------- ### Update Settings Source: https://context7.com/flarum/framework/llms.txt Updates the forum's settings. This endpoint is restricted to administrators. ```APIDOC ## POST /api/settings ### Description Updates various forum settings. Requires administrator privileges. ### Method POST ### Endpoint /api/settings #### Request Body - **forum_title** (string) - Optional - The new title for the forum. - **welcome_message** (string) - Optional - The welcome message displayed to new users. - **default_locale** (string) - Optional - The default language for the forum. ### Request Example ```bash curl -X POST https://forum.example.com/api/settings \ -H "Content-Type: application/json" \ -H "Authorization: Token YOUR_ADMIN_API_TOKEN" \ -d '{ "forum_title": "My Forum", "welcome_message": "Welcome to our community!", "default_locale": "en" }' ``` ``` -------------------------------- ### User Avatar Upload Source: https://context7.com/flarum/framework/llms.txt Uploads an avatar for a user. Requires authentication and user permission to upload avatars. ```APIDOC ## POST /users/{id}/avatar ### Description Uploads a new avatar for the specified user. ### Method POST ### Endpoint /users/{id}/avatar #### Path Parameters - **id** (integer) - Required - The ID of the user whose avatar is to be uploaded. #### Request Body - **avatar** (file) - Required - The avatar image file to upload. ### Request Example ```bash curl -X POST https://forum.example.com/api/users/1/avatar \ -H "Content-Type: multipart/form-data" \ -H "Authorization: Token YOUR_API_TOKEN" \ -F "avatar=@/path/to/your/avatar.jpg" ``` ### Response #### Success Response (200) Returns the updated user resource. - **data** (object) - The user resource with updated avatar information. #### Response Example ```json { "data": { "type": "users", "id": "1", "attributes": { "avatarUrl": "https://forum.example.com/avatars/1/your-avatar.jpg" } } } ``` ``` -------------------------------- ### Send User Confirmation Email Source: https://context7.com/flarum/framework/llms.txt Sends a confirmation email to a user. This endpoint can only be accessed by the user themselves or an administrator. ```APIDOC ## POST /users/{id}/send-confirmation ### Description Sends a confirmation email to the specified user. The user must not have already confirmed their email, and the actor must be the user themselves or an administrator. ### Method POST ### Endpoint /users/{id}/send-confirmation #### Path Parameters - **id** (integer) - Required - The ID of the user to send the confirmation email to. ### Request Example ```bash curl -X POST https://forum.example.com/api/users/1/send-confirmation \ -H "Authorization: Token YOUR_API_TOKEN" ``` ### Response #### Success Response (200) Returns a JSON object indicating success. - **success** (boolean) - Indicates if the email sending process was initiated successfully. #### Response Example ```json { "success": true } ``` ``` -------------------------------- ### API Resource Extension Source: https://context7.com/flarum/framework/llms.txt Extends existing API resources by adding new fields and configuring endpoints. ```APIDOC ## API Resource Extension ### Description Adds custom fields to API resources and configures their behavior, including inclusion and eager loading. ### Method `ExtendApiResource` ### Endpoint Configurable via the `ExtendApiResource` class. ### Parameters N/A ### Request Example ```php (new Extend\ApiResource(Resource\DiscussionResource::class)) ->fields(fn () => [ Schema\Boolean::make('isLiked') ->get(fn (Discussion $discussion, Context $context) => $discussion->likes()->where('user_id', $context->getActor()->id)->exists() ), Schema\Integer::make('likeCount') ->get(fn (Discussion $discussion) => $discussion->likes()->count()), Schema\Relationship\ToMany::make('tags') ->includable() ]) ->endpoint(Endpoint\Index::class, function (Endpoint\Index $endpoint) { return $endpoint ->addDefaultInclude(['tags', 'user']) ->eagerLoad('likes'); }) ``` ### Response N/A ``` -------------------------------- ### Update Post Source: https://context7.com/flarum/framework/llms.txt Updates an existing post with new content. ```APIDOC ## PATCH /api/posts/{id} ### Description Updates the content of a specific post. ### Method PATCH ### Endpoint /api/posts/{id} #### Path Parameters - **id** (integer) - Required - The ID of the post to update. #### Request Body - **data** (object) - Required - The post payload. - **type** (string) - Required - Must be 'posts'. - **id** (string) - Required - The ID of the post. - **attributes** (object) - Required - Attributes to update. - **content** (string) - Required - The updated content for the post. ### Request Example ```bash curl -X PATCH https://forum.example.com/api/posts/42 \ -H "Content-Type: application/json" \ -H "Authorization: Token YOUR_API_TOKEN" \ -d '{ "data": { "type": "posts", "id": "42", "attributes": { "content": "Updated post content" } } }' ``` ``` -------------------------------- ### TypeScript Jest Configuration for Flarum Extensions (JSON) Source: https://github.com/flarum/framework/blob/2.x/js-packages/jest-config/README.md This JSON configuration extends the base tsconfig.json and includes specific settings for Jest testing with TypeScript in Flarum extensions. It targets test files within the 'tests' directory and includes necessary shims. ```json { "extends": "./tsconfig.json", "include": ["tests/**/*"], "files": ["../../../node_modules/@flarum/jest-config/shims.d.ts"] } ``` -------------------------------- ### Extend Flarum Prettier Config in .prettierrc.js Source: https://github.com/flarum/framework/blob/2.x/js-packages/prettier-config/README.md Extends the default Flarum Prettier configuration by importing it and then overriding specific rules in a .prettierrc.js file. This allows for project-specific customization while retaining the base Flarum standards. Ensure the 'prettier' key is removed from package.json when using this method. ```javascript // .prettierrc.js module.exports = { ...require("@flarum/prettier-config"), semi: false, }; ``` -------------------------------- ### Mark Notifications as Read Source: https://context7.com/flarum/framework/llms.txt Marks all of the current user's notifications as read. ```APIDOC ## POST /api/notifications/read ### Description Marks all unread notifications for the currently authenticated user as read. ### Method POST ### Endpoint /api/notifications/read ### Request Example ```bash curl -X POST https://forum.example.com/api/notifications/read \ -H "Authorization: Token YOUR_API_TOKEN" ``` ``` -------------------------------- ### Model Visibility Extension Source: https://context7.com/flarum/framework/llms.txt Controls the visibility of model data based on user permissions and scopes. ```APIDOC ## Model Visibility Extension ### Description Filters model data based on user permissions, ensuring that users only see what they are allowed to. ### Method `ExtendModelVisibility` ### Endpoint N/A (Data visibility configuration) ### Parameters N/A ### Request Example ```php (new Extend\ModelVisibility(Discussion::class)) ->scopeAll(function (User $actor, Builder $query) { if (!$actor->hasPermission('viewPrivateDiscussions')) { $query->where('is_private', false); } }) ``` ### Response N/A ``` -------------------------------- ### Notification Extension Source: https://context7.com/flarum/framework/llms.txt Registers custom notification types and their delivery methods. ```APIDOC ## Notification Extension ### Description Defines custom notification types and specifies how they should be delivered (e.g., alert, email). ### Method `ExtendNotification` ### Endpoint N/A (Notification configuration) ### Parameters N/A ### Request Example ```php (new Extend\Notification()) ->type(CustomNotification::class, ['alert', 'email']) ``` ### Response N/A ``` -------------------------------- ### Delete Discussion Source: https://context7.com/flarum/framework/llms.txt Deletes a specific discussion thread. ```APIDOC ## DELETE /api/discussions/{id} ### Description Deletes a specified discussion thread and all its associated posts. ### Method DELETE ### Endpoint /api/discussions/{id} #### Path Parameters - **id** (integer) - Required - The ID of the discussion to delete. ### Request Example ```bash curl -X DELETE https://forum.example.com/api/discussions/10 \ -H "Authorization: Token YOUR_API_TOKEN" ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.