Update
This commit is contained in:
@@ -0,0 +1,11 @@
|
|||||||
|
{
|
||||||
|
"mcpServers": {
|
||||||
|
"laravel-boost": {
|
||||||
|
"command": "php",
|
||||||
|
"args": [
|
||||||
|
"artisan",
|
||||||
|
"boost:mcp"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,293 @@
|
|||||||
|
---
|
||||||
|
name: deploying-to-cloud
|
||||||
|
description: "Deploys and manages Laravel applications on Laravel Cloud using the `cloud` CLI. Use when the user wants to deploy an app, ship to Cloud, create or manage applications, environments, databases, caches, object storage, queues, domains, instances, background processes, secrets, compute, scheduled tasks, or Laravel Cloud infrastructure; or check billing, usage, or spend. Triggers on deployment, shipping, Cloud management, environment setup, database provisioning, billing or usage queries, the `cloud` CLI, and Laravel Cloud deployment troubleshooting."
|
||||||
|
license: MIT
|
||||||
|
metadata:
|
||||||
|
author: laravel
|
||||||
|
---
|
||||||
|
|
||||||
|
# Deploying with Laravel Cloud
|
||||||
|
|
||||||
|
Use the [Laravel Cloud documentation](https://cloud.laravel.com/docs/llms.txt) for detailed, current feature behavior. Use the Cloud CLI for Cloud operations rather than guessing dashboard or API workflows. Install it in the project and invoke it as `./vendor/bin/cloud` by default; use a globally installed `cloud` command only as a fallback. Commands below are written as `cloud` for brevity; run them as `./vendor/bin/cloud` unless falling back to the global installation.
|
||||||
|
|
||||||
|
## Application Setup
|
||||||
|
|
||||||
|
- Laravel Cloud deploys from GitHub, GitLab, or Bitbucket. A new Laravel application requires PHP 8.2 or later, Laravel 9 or later, a connected Git provider, and a deployment region.
|
||||||
|
- Cloud creates environments for applications. Use separate production, staging, and preview environments; each environment has its own compute, resources, and deployment settings.
|
||||||
|
- Keep application compute and attached resources in the same region where possible.
|
||||||
|
- Cloud builds a Docker image using the selected PHP version, runs the configured build and deploy commands, and switches traffic to a successful deployment with zero downtime. Push-to-deploy is enabled by default, and manual deployments and deploy hooks are also available.
|
||||||
|
|
||||||
|
## Build and Deploy
|
||||||
|
|
||||||
|
- A typical Laravel build command is `composer install --no-dev && npm run build`.
|
||||||
|
- Run optimization and cache-building commands during the build, not during deployment. A typical deploy command is `php artisan migrate --force`.
|
||||||
|
- Build and deploy commands have a 15-minute timeout. Deploy commands run immediately before the release becomes live, and filesystem changes made by deploy commands are not persisted.
|
||||||
|
- Do not add `php artisan queue:restart`, `php artisan horizon:terminate`, `php artisan optimize:clear`, or `php artisan storage:link` to deploy commands. Cloud handles worker restarts and process management; deploy filesystem changes are not persistent.
|
||||||
|
- After changing environment settings, attached resources, or linked secrets, redeploy the environment for the changes to take effect.
|
||||||
|
|
||||||
|
## Configuration and Resources
|
||||||
|
|
||||||
|
- Attached databases, caches, and object storage inject their connection variables automatically. Custom environment variables take precedence over injected values.
|
||||||
|
- Use Secrets Manager for encrypted organization-level values shared across environments. Secret values cannot be read after creation; redeploy affected environments after creating, updating, linking, unlinking, or deleting a secret.
|
||||||
|
- Environment filesystems are ephemeral and are not shared between replicas. Use a database or Laravel Valkey for persistent cache and sessions, and Laravel Cloud Object Storage for persistent files. Do not rely on local files surviving a deployment.
|
||||||
|
|
||||||
|
### Object Storage and File Visibility
|
||||||
|
|
||||||
|
- Laravel Cloud Object Storage is backed by Cloudflare R2. R2 applies visibility at the bucket level; a bucket cannot contain a mix of private and public objects.
|
||||||
|
- For private files, always use `Storage::disk()` with no arguments, such as `Storage::disk()->put(...)`, so Laravel uses the environment's default disk. Do not pass a disk name for private/default storage. Attach a private Cloud bucket as the environment's default disk.
|
||||||
|
- For public files, use the named public disk: `Storage::disk('public')->put(...)`. Attach a second Cloud bucket configured as public and give it the `public` disk name.
|
||||||
|
- Applications that use both private and public files therefore need two Cloud Object Storage buckets attached to the environment: a private default bucket and a public bucket named `public`.
|
||||||
|
- Do not set per-file or Flysystem `visibility: 'public'` configuration for Cloud Object Storage. R2 does not support per-object ACL headers and rejects those requests; select the bucket visibility when creating the bucket.
|
||||||
|
- Private buckets are not internet-accessible, but Laravel can generate temporary public URLs with `Storage::temporaryUrl(...)`. Public buckets expose all objects through their Cloud-provided public URL.
|
||||||
|
- Install the S3 Flysystem adapter before using Cloud Object Storage: `composer require league/flysystem-aws-s3-v3 "^3.0" --with-all-dependencies`.
|
||||||
|
|
||||||
|
## Queues and Scheduling
|
||||||
|
|
||||||
|
- Managed queues are the recommended queue option. They provision dedicated workers and autoscale based on queued work.
|
||||||
|
- Managed queues require a supported recent Laravel version and `aws/aws-sdk-php`; check the current Cloud documentation before changing dependencies.
|
||||||
|
- Enable the scheduler on an App or Worker cluster to run `php artisan schedule:run` every minute. When an environment has multiple replicas, use Laravel's `onOneServer` for tasks that must run once.
|
||||||
|
- Only Flex compute sizes can scale to zero. Scale-to-zero environments wake for Laravel scheduled tasks and queued jobs, but long-running jobs may be interrupted when the sleep timeout is reached. Use managed queues for workloads that must not be interrupted.
|
||||||
|
|
||||||
|
## Domains and Storage
|
||||||
|
|
||||||
|
- Each environment receives a `laravel.cloud` domain after its first successful deployment. Cloud automatically verifies custom domains and provisions SSL after the required DNS records are configured.
|
||||||
|
- Do not use the ephemeral filesystem for persistent uploads, generated files, cache, or session data. Use the appropriate Cloud resource instead.
|
||||||
|
|
||||||
|
## Cloud CLI
|
||||||
|
|
||||||
|
### Setup
|
||||||
|
|
||||||
|
```shell
|
||||||
|
composer require --dev laravel/cloud-cli
|
||||||
|
./vendor/bin/cloud auth -n
|
||||||
|
```
|
||||||
|
|
||||||
|
If a project-local installation is not available, install the CLI globally with `composer global require laravel/cloud-cli` and invoke it as `cloud`.
|
||||||
|
|
||||||
|
`cloud auth` opens a browser. If a browser is unavailable, set `LARAVEL_CLOUD_TOKEN` in the environment. It overrides any saved token and writes nothing to disk. To save a token instead, run `cloud auth:token --add --token=<token> -n` or pipe it with `echo "$TOKEN" | cloud auth:token --add -n`.
|
||||||
|
|
||||||
|
### Commands
|
||||||
|
|
||||||
|
Commands follow a CRUD pattern: `resource:list`, `resource:get`, `resource:create`, `resource:update`, `resource:delete`.
|
||||||
|
|
||||||
|
Available resources: `application`, `environment`, `instance`, `database-cluster`, `database`, `cache`, `bucket`, `domain`, `websocket-cluster`, `background-process`, `secret`, `command`, `deployment`.
|
||||||
|
|
||||||
|
Some resources have additional commands (e.g., `domain:verify`, `database:open`, `instance:sizes`, `cache:types`, `database:types`, `<resource>:metrics`). Discover these via `cloud -h`.
|
||||||
|
|
||||||
|
Never hardcode command signatures. Always run `cloud <command> -h` to discover options at runtime.
|
||||||
|
|
||||||
|
### CLI Flags
|
||||||
|
|
||||||
|
- Always add `-n` to every command to prevent the CLI from hanging.
|
||||||
|
- Never use `-q` or `--silent`; they suppress all output.
|
||||||
|
|
||||||
|
Flag combos per operation:
|
||||||
|
- Read (`:list`, `:get`) → `--json -n`
|
||||||
|
- Create (`:create`) → `--json -n`
|
||||||
|
- Update (`:update`) → `--json -n --force`
|
||||||
|
- Delete (`:delete`) → `-n --force` (no `--json`)
|
||||||
|
- Environment variables → `-n --force`
|
||||||
|
- Deploy or ship → `-n` with all options passed explicitly (no `--json`)
|
||||||
|
|
||||||
|
### Deployment Workflow
|
||||||
|
|
||||||
|
Determine the task and follow the matching path:
|
||||||
|
|
||||||
|
- First deployment: inspect `cloud ship -h`, then run `cloud ship -n` with all required values.
|
||||||
|
|
||||||
|
- Existing application:
|
||||||
|
```shell
|
||||||
|
cloud deploy {app_name} {environment} -n --open
|
||||||
|
cloud deploy:monitor -n
|
||||||
|
```
|
||||||
|
|
||||||
|
- Environment variables: `cloud environment:variables -n --force`. To copy keys from the local `.env` and deploy in one step: `cloud deploy {app_name} {environment} -n --push-env-keys=KEY_ONE,KEY_TWO`
|
||||||
|
|
||||||
|
- Secrets: `echo "$VALUE" | cloud secret:create --name=NAME --json -n`, then `cloud environment-secret:attach`
|
||||||
|
|
||||||
|
- Provision infrastructure: `cloud <resource>:create --json -n`
|
||||||
|
|
||||||
|
- Monorepo (application in a subdirectory): add `--root-directory=<subdir>` to `cloud ship` or `cloud application:create`.
|
||||||
|
|
||||||
|
- Custom domain: `cloud domain:create --json -n`, then `cloud domain:verify -n`.
|
||||||
|
|
||||||
|
- Edge cache: `cloud environment:purge-edge-cache {environment} -n` purges everything; pass one of `--path=/blog/post`, `--prefix=/blog/`, or `--tag=<cache-tag>` to purge less. Tags need a dedicated edge network.
|
||||||
|
|
||||||
|
- Laravel Cloud domain: `cloud environment:vanity-domain {environment} --name=<subdomain> --deploy -n --force`. Pass only the first part of the domain. The new domain takes effect on the next deploy, which `--deploy` starts and monitors. It can change only once every 30 minutes, so confirm with the user first.
|
||||||
|
|
||||||
|
- Repository defaults: `cloud repo:config {application} -n` sets repository-local application and organization defaults. Pass `--organization=<id|name|slug>` when the user has multiple organizations.
|
||||||
|
|
||||||
|
For multi-step operations, see [reference/checklists.md](reference/checklists.md).
|
||||||
|
|
||||||
|
- If the user's needs are unclear, ask before running anything.
|
||||||
|
|
||||||
|
### When a Command Fails
|
||||||
|
|
||||||
|
1. Read the error output.
|
||||||
|
2. Check the resource status with `:list --json -n` or `:get --json -n`.
|
||||||
|
3. For authentication errors, run `cloud auth -n`.
|
||||||
|
4. Fix the issue and rerun the command.
|
||||||
|
5. If the same error occurs after one fix, stop and ask the user rather than repeating the operation.
|
||||||
|
|
||||||
|
Always run `cloud deploy:monitor -n` after every deploy. If it fails, run `cloud deployment:logs {deploymentId} --json -n` to find the build or deploy step with `"status": "failed"` and read its `output`. Show the user what went wrong before attempting a fix.
|
||||||
|
|
||||||
|
### Subagent Delegation
|
||||||
|
|
||||||
|
Delegate high-output operations to subagents using the Task tool to keep the main context window small. Only the summary returns; verbose output stays in the subagent's context.
|
||||||
|
|
||||||
|
Delegate these to a subagent:
|
||||||
|
- `cloud deploy:monitor -n` — deployment logs can be very long
|
||||||
|
- `cloud deployment:get --json -n` — full deployment details
|
||||||
|
- `cloud deployment:logs --json -n` — every step's full build or deploy output
|
||||||
|
- `cloud <resource>:list --json -n` — listing many resources produces large JSON
|
||||||
|
- `cloud <resource>:metrics --json -n` — every data point is included; narrow it with `--fields` (e.g. `--fields=period,cpuUsage.average`)
|
||||||
|
- `cloud command:run` — when output may be long
|
||||||
|
- `cloud usage --detailed --json -n` — the payload includes details for every database, cache, bucket, websocket, and application
|
||||||
|
- Fetching docs from https://cloud.laravel.com/docs/llms.txt via `WebFetch`
|
||||||
|
|
||||||
|
Keep in the main context:
|
||||||
|
- Short commands like `:create`, `:delete`, `:update` — output is small
|
||||||
|
- `cloud deploy -n` — you need the deployment ID immediately
|
||||||
|
- Any command where you need the result for the next step right away
|
||||||
|
|
||||||
|
### Rules
|
||||||
|
|
||||||
|
Follow these rules:
|
||||||
|
- Flag selection — always use the documented combos above
|
||||||
|
- Deploy sequence — deploy then monitor, never skip monitoring
|
||||||
|
- Destructive commands — always confirm with the user first, show the command and wait for approval. This includes deleting applications, environments, databases, caches, buckets, domains, or secrets, and detaching Resend.
|
||||||
|
- Error loop — diagnose, fix once, ask user if it fails again
|
||||||
|
|
||||||
|
Use judgment for:
|
||||||
|
- Instance sizes, regions, cluster types — ask the user if not specified
|
||||||
|
- Which resources to provision — based on what the user describes
|
||||||
|
- Order of provisioning — no strict sequence required
|
||||||
|
- How to present output — summarize, show raw, or extract fields based on context
|
||||||
|
|
||||||
|
### Secrets
|
||||||
|
|
||||||
|
Secrets are encrypted values shared across the organization and attached to environments. The CLI encrypts values locally, so plaintext never reaches the API.
|
||||||
|
|
||||||
|
```shell
|
||||||
|
cloud secret:list --json -n
|
||||||
|
echo "$VALUE" | cloud secret:create --name=STRIPE_KEY --json -n
|
||||||
|
cloud environment-secret:attach {environment} {secretId} -n
|
||||||
|
cloud environment-secret:detach {environment} {secretId} --force -n
|
||||||
|
cloud environment-secret:list {environment} --json -n
|
||||||
|
```
|
||||||
|
|
||||||
|
Pipe the value in. `--value=` works, but leaves the plaintext in shell history and the process list.
|
||||||
|
|
||||||
|
`secret:update`, `secret:delete`, `environment-secret:attach`, and `environment-secret:detach` take secret IDs, not names — names are not unique. Read IDs from `cloud secret:list --json -n`.
|
||||||
|
|
||||||
|
There is no `secret:get`. `environment-secret:detach` removes a secret from one environment and keeps it; `secret:delete` deletes it and detaches it everywhere.
|
||||||
|
|
||||||
|
Secrets need the `sodium` PHP extension. No other command does.
|
||||||
|
|
||||||
|
Redeploy affected environments after creating, updating, attaching, detaching, or deleting a secret.
|
||||||
|
|
||||||
|
### Email (Resend)
|
||||||
|
|
||||||
|
Resend sends an environment's email. Connecting a Resend account and verifying sending domains happen in the dashboard; the CLI cannot do either. When `resend:attach` reports no verified sending domains, give the user the integration settings link from the error.
|
||||||
|
|
||||||
|
```shell
|
||||||
|
cloud resend:domains --status=verified --json -n
|
||||||
|
cloud resend:attach {environment} --from-address=hello@{verifiedDomain} --from-name="My App" --json -n
|
||||||
|
cloud resend:update {environment} --from-address=team@{verifiedDomain} --json -n
|
||||||
|
cloud resend:keys {environment} --json -n
|
||||||
|
cloud resend:detach {environment} --force -n
|
||||||
|
```
|
||||||
|
|
||||||
|
- The sender address must use a verified sending domain. `--from-name` defaults to the application name.
|
||||||
|
- `resend:attach` creates a new sending key. To share one with another environment, pass `--reuse-key-id` with an ID from `resend:keys`.
|
||||||
|
- Attaching makes Cloud set `RESEND_API_KEY`, `MAIL_MAILER`, `MAIL_FROM_ADDRESS`, and `MAIL_FROM_NAME`, replacing any the environment already had.
|
||||||
|
- The application needs `resend/resend-php`. Under `-n`, `resend:attach` only warns when it is missing; run `composer require resend/resend-php` in the project.
|
||||||
|
- Detaching deletes the sending key unless another environment uses it.
|
||||||
|
- Redeploy the environment after attaching, updating, or detaching Resend.
|
||||||
|
|
||||||
|
### Remote Access
|
||||||
|
|
||||||
|
#### Tinker (v0.2.0 or later)
|
||||||
|
|
||||||
|
Run PHP code directly in a Cloud environment:
|
||||||
|
|
||||||
|
```shell
|
||||||
|
cloud tinker {environment} --code='Your PHP code here' --timeout=60 -n
|
||||||
|
```
|
||||||
|
|
||||||
|
- `--code` — PHP code to execute (required in non-interactive mode)
|
||||||
|
- `--timeout` — maximum number of seconds to wait for output (default: 60)
|
||||||
|
|
||||||
|
The code must explicitly output results using `echo`, `dump`, or similar; expressions alone produce no output.
|
||||||
|
|
||||||
|
Always pass `--code` and `-n` to avoid interactive prompts.
|
||||||
|
|
||||||
|
#### Remote Commands
|
||||||
|
|
||||||
|
Run shell commands on a Cloud environment:
|
||||||
|
|
||||||
|
```shell
|
||||||
|
cloud command:run {environment} --cmd='your command here' -n
|
||||||
|
```
|
||||||
|
|
||||||
|
- `--cmd` — the command to run (required in non-interactive mode)
|
||||||
|
- `--no-monitor` — skip real-time output streaming
|
||||||
|
- `--copy-output` — copy output to clipboard
|
||||||
|
|
||||||
|
Review past commands:
|
||||||
|
|
||||||
|
- `cloud command:list {environment} --json -n` — list command history
|
||||||
|
- `cloud command:get {commandId} --json -n` — get details and output of a specific command
|
||||||
|
|
||||||
|
### Billing and Usage
|
||||||
|
|
||||||
|
View billing and usage for the current organization:
|
||||||
|
|
||||||
|
```shell
|
||||||
|
cloud usage --json -n
|
||||||
|
```
|
||||||
|
|
||||||
|
- `--period=current|previous|1|2|3` — Billing period (default: `current`; `1`, `2`, and `3` are one, two, and three periods back, respectively). Other values return an error.
|
||||||
|
- `--environment=<id>` — filter usage to a single environment
|
||||||
|
- `--detailed` — include per-application, per-resource, and per-add-on breakdowns
|
||||||
|
- `--json` — machine-readable output (always pair with `-n`)
|
||||||
|
|
||||||
|
Common queries:
|
||||||
|
|
||||||
|
- Current spend: `cloud usage --json -n | jq '.currentSpendCents'`
|
||||||
|
- Last month's bill: `cloud usage --period=previous --json -n`
|
||||||
|
- One environment, full breakdown: `cloud usage --environment=<id> --detailed --json -n`
|
||||||
|
|
||||||
|
All amounts are in cents. Keys are camelCase at every level (e.g., `currentSpendCents`, `bandwidth.allowanceBytes`, `databases[].totalCents`, `applications[].totalCostCents`).
|
||||||
|
|
||||||
|
### Config
|
||||||
|
|
||||||
|
1. Environment: `LARAVEL_CLOUD_TOKEN` — an API token, taking precedence over any saved one (empty counts as unset)
|
||||||
|
2. Global: `~/.config/cloud/config.json` — auth tokens and preferences
|
||||||
|
3. Repo-local: `.cloud/config.json` — app and environment defaults (set by `cloud repo:config {application} -n`)
|
||||||
|
4. CLI arguments override both config files
|
||||||
|
|
||||||
|
Pass the application to `repo:config`. Without it, the command must prompt and fails under `-n` when the organization has more than one application. Deploy commands do not need these defaults; pass the application and environment to them directly.
|
||||||
|
|
||||||
|
Using multiple organizations requires multiple stored API tokens. Commands read `organization_id` from `.cloud/config.json` to select one and fail if it is not set. Set it with `cloud repo:config {application} --organization=<id|name|slug> -n`.
|
||||||
|
|
||||||
|
`LARAVEL_CLOUD_TOKEN` holds one token, so it picks the organization on its own. Naming a different one with `--organization` fails rather than falling back to the token's organization.
|
||||||
|
|
||||||
|
## Documentation
|
||||||
|
|
||||||
|
Laravel Cloud documentation: https://cloud.laravel.com/docs/llms.txt
|
||||||
|
|
||||||
|
When the user asks how something works or needs an explanation of a Laravel Cloud feature, fetch the docs from the URL above using `WebFetch` and use it to provide accurate answers.
|
||||||
|
|
||||||
|
## When Stuck
|
||||||
|
|
||||||
|
- Fetch https://cloud.laravel.com/docs/llms.txt for official documentation
|
||||||
|
- Run `cloud <command> -h` for any command's options
|
||||||
|
- Run `cloud -h` to discover commands
|
||||||
|
|
||||||
|
## Verification
|
||||||
|
|
||||||
|
1. Confirm the target application and environment before changing or deploying anything.
|
||||||
|
2. Check staged environment changes and required resources before deployment.
|
||||||
|
3. Monitor every deployment to completion with `cloud deploy:monitor -n`.
|
||||||
|
4. For production changes, verify the application URL, logs, queues, scheduled tasks, and relevant resource health.
|
||||||
@@ -0,0 +1,65 @@
|
|||||||
|
# Checklists for Multi-Step Operations
|
||||||
|
|
||||||
|
Use these checklists when performing complex setups. Copy the relevant checklist and track progress as you go.
|
||||||
|
|
||||||
|
## Full environment setup (app + database + cache + domain)
|
||||||
|
|
||||||
|
```
|
||||||
|
- [ ] Create or select the application
|
||||||
|
- [ ] Create the environment
|
||||||
|
- [ ] Provision the database (`database-cluster:create` then `database:create`)
|
||||||
|
- [ ] Provision the cache (`cache:create`)
|
||||||
|
- [ ] Set environment variables (`environment:variables`)
|
||||||
|
- [ ] Create and attach any secrets (`secret:create` then `environment-secret:attach`)
|
||||||
|
- [ ] Attach custom domain (`domain:create` then `domain:verify`)
|
||||||
|
- [ ] Deploy (`deploy` then `deploy:monitor`)
|
||||||
|
- [ ] Verify the deployment is live
|
||||||
|
```
|
||||||
|
|
||||||
|
## New app from scratch
|
||||||
|
|
||||||
|
```
|
||||||
|
- [ ] Run `cloud ship -n` with required options
|
||||||
|
- [ ] Monitor deployment status
|
||||||
|
- [ ] Set environment variables if needed
|
||||||
|
- [ ] Verify the app is accessible
|
||||||
|
```
|
||||||
|
|
||||||
|
## Adding a database to an existing environment
|
||||||
|
|
||||||
|
```
|
||||||
|
- [ ] Check existing database clusters (`database-cluster:list --json -n`)
|
||||||
|
- [ ] Create a new cluster if needed (`database-cluster:create --json -n`)
|
||||||
|
- [ ] Create the database on the cluster (`database:create --json -n`)
|
||||||
|
- [ ] Update environment variables with connection details if needed
|
||||||
|
- [ ] Redeploy if the app needs to pick up new config
|
||||||
|
```
|
||||||
|
|
||||||
|
## Adding a cache to an existing environment
|
||||||
|
|
||||||
|
```
|
||||||
|
- [ ] Check existing caches (`cache:list --json -n`)
|
||||||
|
- [ ] Create the cache (`cache:create --json -n`)
|
||||||
|
- [ ] Update environment variables with cache connection details if needed
|
||||||
|
- [ ] Redeploy if the app needs to pick up new config
|
||||||
|
```
|
||||||
|
|
||||||
|
## Sending email with Resend
|
||||||
|
|
||||||
|
```
|
||||||
|
- [ ] Check for verified sending domains (`resend:domains --status=verified --json -n`)
|
||||||
|
- [ ] If there are none, send the user to the dashboard to connect Resend and verify a domain
|
||||||
|
- [ ] Attach Resend (`resend:attach {environment} --from-address=... --json -n`)
|
||||||
|
- [ ] Install `resend/resend-php` in the project if it is missing
|
||||||
|
- [ ] Commit and redeploy (`deploy` then `deploy:monitor`)
|
||||||
|
```
|
||||||
|
|
||||||
|
## Custom domain setup
|
||||||
|
|
||||||
|
```
|
||||||
|
- [ ] Create the domain (`domain:create --json -n`)
|
||||||
|
- [ ] Get DNS records to configure (`domain:get --json -n`)
|
||||||
|
- [ ] Tell the user to add the DNS records at their registrar
|
||||||
|
- [ ] Verify the domain (`domain:verify -n`)
|
||||||
|
- [ ] Confirm verification passed
|
||||||
|
```
|
||||||
@@ -0,0 +1,105 @@
|
|||||||
|
---
|
||||||
|
name: infer-conventions
|
||||||
|
description: "Use this skill to analyze how a Laravel application is actually written and record its conventions as shared rules. Trigger when the user wants to detect, infer, document, or standardize project conventions or coding style, set up or grow `.ai/rules`, resolve mixed or conflicting patterns (e.g. \"are we using Form Requests or inline validation?\"), or onboard agents and teammates to \"how we do things here\". Covers: a systematic sweep of ~49 Laravel convention dimensions (validation, models, architecture, testing, frontend, database, API responses), open-ended house-pattern discovery, conflict reporting, and recording rules scoped to the right paths via the Boost `record-rule` MCP tool. Only run this skill when the user explicitly asks for it; never start a sweep as part of another task. Do not use for one-off code review, enforcing formatting a linter already handles, or editing `.ai/rules` files by hand."
|
||||||
|
disable-model-invocation: true
|
||||||
|
license: MIT
|
||||||
|
metadata:
|
||||||
|
author: laravel
|
||||||
|
---
|
||||||
|
|
||||||
|
# Infer conventions
|
||||||
|
|
||||||
|
Learn how this application writes Laravel, then record what you learn as durable, path-scoped rules other agents will read. You are documenting reality, not improving it.
|
||||||
|
|
||||||
|
## Ground rules (read before you start)
|
||||||
|
|
||||||
|
- Consistency first. The codebase's majority style is the convention. Never judge it, never propose a "better" pattern, never record what the code should do. If the app validates inline everywhere, that is the rule, even if Form Requests would be nicer.
|
||||||
|
- Skip what an active tool produces, keep what a tool would fight. Inspect the project's Pint and Rector configuration first. A Rector transformation is tooling-owned only when its package and relevant rule or set are installed and enabled. Active tools may rewrite code toward one canonical form: `$casts` to `casts()`, `$fillable` to attributes, magic accessors to the `Attribute` class, pipe-string rules to arrays, `$signature` to `#[Signature]`, named migrations to anonymous, and many more. When the app already sits at an active tool's target form, the tool owns it, so record nothing. But when the app deliberately holds a form an active tool would refactor away, such as legacy `getXxxAttribute()` accessors the `Attribute` class would replace, no tool can reproduce that choice and an agent defaults the other way. Record that against-the-grain hold.
|
||||||
|
- Record decisions, not defaults. A consistent pattern earns a rule only when it reflects a choice: the app took one valid option where the framework or common practice offered others, or the pattern would surprise a competent agent. Framework defaults steer nothing, so skip them: anonymous migrations, `$signature` commands, `ShouldQueue` jobs, `casts()` on Laravel 11+, named routes, Rule objects in `app/Rules`, and `Mail::fake()` or `Bus::fake()` to isolate framework services. A real fork is not enough on its own. Weigh the side the app took, and record only the side an agent would not reach for by itself: inline closures everywhere, legacy accessors, a bespoke query layer. Watch for the false fork too. "No Mockery" next to facade fakes is not a choice against Mockery, because they double different things. The test for every candidate: without this rule, would the next agent plausibly write it differently? Only "yes" earns a rule.
|
||||||
|
- Architecture choices are the gold. Record presence and deliberate absence. The structural pattern the app commits to is the highest-signal convention and the one no tool can decide: Action classes and how they are invoked (`handle` / `execute` / `__invoke`), service objects, dedicated query objects exposing `builder()`, DTOs (spatie/laravel-data vs readonly classes), Form Request validation vs inline, an events and listeners spine vs direct calls, and domain or module folders. Also record a consistent non-pattern, such as "query Eloquent directly in controllers, no repository layer", so the next agent matches the app's altitude instead of over-engineering.
|
||||||
|
- Never duplicate `.ai/rules`. Read `.ai/rules/index.md` and the area files before the sweep. A dimension already covered there is marked done and skipped.
|
||||||
|
- Evidence or silence. A convention needs at least 3 consistent examples and no meaningful rival to become a candidate. Every Step 1 verdict applies this bar.
|
||||||
|
- The recorded rule states the convention, nothing else. One or two imperative lines: this project does X, so do X here. Keep detection evidence out. No counts, ratios, current usage, file lists, or example paths, because that is proof for the confirm step, not part of the rule. One short syntax fragment at most, and point to `search-docs` for API details.
|
||||||
|
|
||||||
|
## Process
|
||||||
|
|
||||||
|
Each step ends on a checkable completion criterion. Do not advance until it holds.
|
||||||
|
|
||||||
|
Fan out when you can. The checklist groups are independent, so they can run in parallel. If your environment can spawn subagents (a Task, dispatch, or equivalent tool), do Step 0 yourself, then hand each checklist group (A to J) and the architecture map to its own subagent. Each subagent runs the greps, reads a few representative files, and returns structured verdicts (dimension, verdict, evidence, proposed glob / title / note). You aggregate, dedupe, then run Steps 3 to 5. Fanning out is much faster on a real app. Without subagents, run the steps in sequence, with the same bar and the same output.
|
||||||
|
|
||||||
|
### Step 0: Orient
|
||||||
|
|
||||||
|
Read `composer.json` (installed packages tell you which checklist groups apply), the `pint.json` / PHPStan / Rector config, `.ai/rules/index.md` if present, and most important, map the `app/` tree. List every directory under `app/` (and any `Modules/`, `src/`, `packages/`, or domain root). Every folder beyond Laravel's default skeleton (`Http`, `Models`, `Providers`, `Console`, `Exceptions`) is a structural pattern the app committed to and a candidate for a high-value rule: `Actions`, `Services`, `Data` or DTOs, `Queries`, `Repositories`, `ViewModels`, `Pipelines`, `Support`, `Enums`, `Contracts`, `Observers`, or `Domain` and module roots. Note each one. You will confirm how it is used in Step 2.
|
||||||
|
|
||||||
|
This app has no Livewire/Inertia/Flux packages installed. Treat the frontend group as likely API-only: confirm from `resources/views` before spending time there, and skip the Livewire/Inertia/Flux dimensions.
|
||||||
|
|
||||||
|
Done when: you have the applicable checklist groups, the dimensions already recorded in `.ai/rules`, and a list of every non-default `app/` directory mapped to the pattern it represents.
|
||||||
|
|
||||||
|
### Step 1: Predefined sweep
|
||||||
|
|
||||||
|
Open `references/checklist.md` and work every applicable dimension using its search hints. Give each exactly one verdict:
|
||||||
|
|
||||||
|
- Pattern. Clears the bar, rival under ~20% of sites, and reflects a real choice (passes the decisions-not-defaults test). A recording candidate. Cite 2 to 3 example files.
|
||||||
|
- Conflict. Both styles present in meaningful numbers. Report the split with counts and example files. Never record a preferred winner while the code remains mixed, even in yolo, because that would describe an aspiration rather than reality. Record only if the user identifies a stable path or context boundary that explains both styles. Otherwise, defer until the code is reconciled.
|
||||||
|
- Default. Consistent, but a framework or common-practice default the agent already writes unprompted. Skip it as a no-op, not a convention.
|
||||||
|
- No signal. Under the bar: feature unused, or too few examples. Skip silently (one summary line at most).
|
||||||
|
- Tooling-owned or Already-recorded. Skip per the ground rules.
|
||||||
|
|
||||||
|
Done when: every applicable dimension carries exactly one of those verdicts.
|
||||||
|
|
||||||
|
### Step 2: Open-ended pass
|
||||||
|
|
||||||
|
First, close out the architecture map from Step 0. For every non-default `app/` directory you listed, confirm how the pattern is used and apply the same evidence and decisions-not-defaults tests as Step 1. Generator-standard or sparsely used directories such as `Rules`, `Observers`, `Mail`, and `Notifications` are signals to inspect, not automatic conventions. Make genuine structural patterns candidates: Action classes invoked via `handle` / `execute` / `__invoke`, Services constructor-injected, `Queries` objects exposing `builder(): Builder`, DTOs as readonly classes or spatie/laravel-data, module or domain folders as the unit of organization. Scope each qualifying pattern to its own directory glob. Also record a consistent deliberate absence, such as "no repository layer, controllers query Eloquent directly", so the next agent matches the app's altitude.
|
||||||
|
|
||||||
|
Then find the other patterns specific to this codebase: base or abstract classes most code extends, traits used everywhere, tenancy or authorization scoping woven through queries, naming schemes, and custom helpers. Same evidence bar, cite files. Record every genuine structural pattern, and cap the other house findings at ~5 so the pass stays high-signal.
|
||||||
|
|
||||||
|
Done when: every non-default `app/` directory from Step 0 has a verdict, and the pass has produced its cited house findings (or concluded there are none).
|
||||||
|
|
||||||
|
### Step 3: Confirm
|
||||||
|
|
||||||
|
Present every candidate in one batch. Per item: dimension, verdict, evidence (counts and files), and the exact proposed `glob` or `globs` / `title` / `note`. Present conflicts as questions about an existing context boundary or deferred cleanup, not as a choice of future style.
|
||||||
|
|
||||||
|
Default mode is confirm: record only what the user approves. Switch to yolo only when the invocation said so ("yolo", "don't ask", "just record them"), then record all pattern candidates without asking. Conflicts still go to the user in yolo.
|
||||||
|
|
||||||
|
Done when: every candidate is approved, rejected, or (conflicts) decided.
|
||||||
|
|
||||||
|
### Step 4: Record
|
||||||
|
|
||||||
|
Make one `record-rule` call for each glob an approved convention applies to. Choose the most specific globs that cover the cited evidence from the mapping table below. If a convention spans models and migrations, record it under both domains so agents discover it from either path. The `note` is the bare convention: strip every trace of detection (see the ground rule). If `record-rule` is unavailable (rules disabled), report the full rule text so the user can enable `BOOST_RULES_ENABLED` or add it by hand.
|
||||||
|
|
||||||
|
Record this:
|
||||||
|
|
||||||
|
> Accessors and mutators: use the legacy magic-method style (`getXxxAttribute()` / `setXxxAttribute()`), not the `Attribute` class. Match it in models.
|
||||||
|
|
||||||
|
Not this:
|
||||||
|
|
||||||
|
> Accessors/mutators use the legacy magic-method style; the `Attribute`-class style is not used anywhere (13 legacy, 0 Attribute-class), e.g. `app/Models/Post.php`. Match the legacy style in existing models.
|
||||||
|
|
||||||
|
Done when: every approved item has a successful tool response, and any failure is reported with its rule text.
|
||||||
|
|
||||||
|
### Step 5: Summarize
|
||||||
|
|
||||||
|
List recorded rules (file and title), conflicts the user deferred, notable no-signals, and remind the user to commit `.ai/rules` so their team and agents share the conventions.
|
||||||
|
|
||||||
|
## Glob mapping
|
||||||
|
|
||||||
|
Attach each rule to the most specific path that covers its evidence. Do not use `app/**` when a subtree fits. Match the glob to where the code lives, which is not the same in a default skeleton and in a modular or DDD layout. Use the Step 0 `app/` map to pick the real path.
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
|
||||||
|
- Models: `app/Models/**` in a default app, or `app/Modules/Blog/Models/**` / `src/Domain/Blog/**` in a modular one.
|
||||||
|
- Controllers, routing, validation, responses: `app/Http/**`, or `app/Modules/*/Http/**` when each module owns its HTTP layer.
|
||||||
|
- Actions, Services, DTOs: `app/Actions/**`, `app/Services/**`, `app/Data/**`, or the module path the app uses.
|
||||||
|
- Tests: `tests/**`.
|
||||||
|
- Migrations and database: `database/migrations/**`.
|
||||||
|
- Truly app-wide (rare, e.g. auth retrieval): `app/**`.
|
||||||
|
|
||||||
|
`record-rule` takes one glob. When a convention spans two domains (e.g. UUID keys touch models and migrations), call it once per domain with the same title and note. Mentioning another path in the note does not make the rule discoverable there.
|
||||||
|
|
||||||
|
## Edge cases
|
||||||
|
|
||||||
|
- Rules disabled or `record-rule` missing: detection is read-only, so Steps 0 to 3 still run, and recording falls back to the manual path in Step 4.
|
||||||
|
- Tiny or fresh app: most dimensions land on no-signal. Say so ("not enough code to infer conventions yet") and record nothing.
|
||||||
|
- Huge app: each dimension is a bounded grep plus a handful of file reads. Sample representative files, do not read everything.
|
||||||
|
- Re-runs: reading `.ai/rules` in Step 0 makes re-runs incremental, so only new or undecided dimensions surface.
|
||||||
|
- Non-standard layout (modules, DDD): the open-ended pass catches the layout itself as convention #1. Adapt the globs in the mapping table to the observed paths.
|
||||||
@@ -0,0 +1,137 @@
|
|||||||
|
# Detection checklist
|
||||||
|
|
||||||
|
Every dimension here is a genuine fork: Laravel offers two or more valid approaches, the app's choice changes what the next agent writes, and no active project tool can pick for you. Left out on purpose: pure formatting (Pint owns it), any form an installed and enabled Rector rule rewrites to one canonical shape (`$casts` to `casts()`, `$fillable` to attributes, pipe-string rules to arrays, named to anonymous migrations, `$signature` to `#[Signature]`), and framework defaults any agent writes unprompted (`ShouldQueue` jobs, relation return types, `HasFactory`).
|
||||||
|
|
||||||
|
Each item gives the fork, then a hint (a grep or dir to spot which side the app takes). Hints are only a start. Read the matched files. Never record on a raw count. Apply the ground rules to every verdict: a consistent choice that is a default or a tool's target form is not a pattern. Rows tagged (architecture) are the highest-signal, so record presence and deliberate absence.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## A. Validation & HTTP input
|
||||||
|
|
||||||
|
1. Validation entry point: inline `$request->validate()` vs Form Request classes vs `Validator::make()`.
|
||||||
|
- Hint: `ls app/Http/Requests`. Grep -- `->validate(` / `Validator::make(` in `app/Http/Controllers`.
|
||||||
|
2. Custom rule location: invokable rule objects in `app/Rules` vs inline closures vs `Validator::extend()` in a provider. Rule objects are the default `make:rule` path, so record only if the app leans on closures or `Validator::extend` instead. "No rule objects" alone is just no-signal.
|
||||||
|
- Hint: `ls app/Rules`. Grep `Validator::extend` in `app/Providers`.
|
||||||
|
3. Typed input retrieval: typed getters (`$request->string()`, `->integer()`, `->enum()`, `->date()`) vs raw `$request->input()` / dynamic properties.
|
||||||
|
- Hint: grep -- `->string(` / `->integer(` / `->enum(` vs `->input(` in `app/Http`.
|
||||||
|
4. Custom messages/attributes: `lang/*/validation.php` vs Form Request `messages()` / `attributes()` methods.
|
||||||
|
- Hint: `ls lang`. Grep `function messages`, `function attributes` in `app/Http/Requests`.
|
||||||
|
|
||||||
|
## B. Controllers & routing
|
||||||
|
|
||||||
|
5. Controller shape: invokable single-action (`__invoke`) vs resource controllers vs plain multi-method.
|
||||||
|
- Hint: grep `__invoke` in controllers. `Route::resource` / `apiResource` vs verb routes.
|
||||||
|
6. Business-logic location (architecture): fat controllers vs delegated to Actions / Services / Jobs.
|
||||||
|
- Hint: read a few controller methods. `ls app/Actions app/Services`.
|
||||||
|
7. Route handler style: closures in `routes/*.php` vs controller classes.
|
||||||
|
- Hint: count `function ()` vs `::class` in `routes/web.php`, `routes/api.php`.
|
||||||
|
8. Middleware assignment: route/group `->middleware()` vs controller `HasMiddleware::middleware()` vs `#[Middleware]` attribute.
|
||||||
|
- Hint: grep -- `implements HasMiddleware`, `#[Middleware(` in controllers vs `->middleware(` in routes.
|
||||||
|
9. Route model binding: implicit (type-hinted models) vs explicit `Route::bind` vs manual `findOrFail`.
|
||||||
|
- Hint: typed model params in signatures vs `findOrFail(` in controllers. Grep `Route::bind`.
|
||||||
|
10. Rate limiting: named `RateLimiter::for()` + `throttle:name` vs inline `throttle:60,1`.
|
||||||
|
- Hint: grep `RateLimiter::for` in providers vs `throttle:` in route files.
|
||||||
|
|
||||||
|
## C. Authorization
|
||||||
|
|
||||||
|
11. Authorization home: Gates (`Gate::define`) vs Policy classes in `app/Policies`.
|
||||||
|
- Hint: `ls app/Policies`. Grep `Gate::define` in `app/Providers`.
|
||||||
|
12. Authorization call site: `$this->authorize()` / `Gate::authorize()` vs `$user->can()` vs `can` middleware vs `#[Authorize]` vs `@can` in Blade.
|
||||||
|
- Hint: grep -- `authorize(`, `->can(`, `middleware('can:`, `#[Authorize(`, `@can(`.
|
||||||
|
|
||||||
|
## D. Eloquent & models
|
||||||
|
|
||||||
|
13. Mass assignment: `$fillable` allow-list vs `$guarded` block-list.
|
||||||
|
- Hint: grep `protected $fillable` / `protected $guarded` in `app/Models`.
|
||||||
|
14. Accessors/mutators: modern `Attribute` class vs legacy `getXxxAttribute()` / `setXxxAttribute()`. Record a legacy hold, because it goes against the tool's grain.
|
||||||
|
- Hint: grep `: Attribute` / `Attribute::make` vs `function get[A-Z].*Attribute` in `app/Models`.
|
||||||
|
15. Primary keys: auto-increment vs `HasUuids` vs `HasUlids`.
|
||||||
|
- Hint: grep `HasUuids` / `HasUlids` in `app/Models`. Migration `id()` vs `uuid('id')`.
|
||||||
|
16. Custom casts: dedicated `CastsAttributes` classes (`app/Casts`) vs inline `Attribute` vs built-in cast strings.
|
||||||
|
- Hint: `ls app/Casts`. Grep `Cast::class`, `AsStringable::class` in models.
|
||||||
|
17. Data/query layer (architecture): Eloquent directly in controllers vs repositories vs dedicated query objects (e.g. classes exposing `builder(): Builder`).
|
||||||
|
- Hint: `ls app/Repositories app/Queries`. See where non-trivial queries are built.
|
||||||
|
18. Query scopes: local `scope`/`#[Scope]` methods vs dedicated builder classes.
|
||||||
|
- Hint: grep `function scope` / `#[Scope]` in models. `ls app/*/Builders`.
|
||||||
|
19. Model events: observers (`app/Observers`, `#[ObservedBy]`) vs `booted()` closures vs event classes.
|
||||||
|
- Hint: `ls app/Observers`. Grep `booted`, `::observe`, `#[ObservedBy]`.
|
||||||
|
20. Eager-load posture: explicit per-query `->with()` vs model-level `$with` defaults. Treat `preventLazyLoading()` separately as a development guard because it can complement either posture.
|
||||||
|
- Hint: grep -- `protected $with`, `->with(`, and separately `preventLazyLoading` in `app/`.
|
||||||
|
|
||||||
|
## E. Architecture & organization
|
||||||
|
|
||||||
|
21. Action/Service structure (architecture): Action classes (invoked via `handle` / `execute` / `__invoke`) vs service objects vs neither. Cross-check the Step 0 `app/` map: any `Actions`/`Services`/`Pipelines`/`Jobs`-as-actions folder is this pattern, so record how it is invoked.
|
||||||
|
- Hint: `ls app/` (the whole tree, not just `Actions`/`Services`). Grep the invocation method in the folder you find.
|
||||||
|
22. DTOs (architecture): spatie/laravel-data vs plain readonly classes vs arrays everywhere.
|
||||||
|
- Hint: `ls app/Data`. Grep `extends Data`, `readonly class` in `app/`.
|
||||||
|
23. Dependency acquisition: constructor/method injection vs `app()` / `resolve()` / `App::make()` service location.
|
||||||
|
- Hint: grep `app(` / `resolve(` / `::make(` in `app/` vs promoted constructor deps.
|
||||||
|
24. Decoupling: events + listeners vs direct service calls.
|
||||||
|
- Hint: `ls app/Events app/Listeners`. Grep `event(`, `::dispatch(`.
|
||||||
|
25. Helper vs facade idiom: global helpers (`config()`, `auth()`, `response()`) vs facades (`Config::`, `Auth::`, `Response::`).
|
||||||
|
- Hint: ratio of `config(` vs `Config::` (etc.) across `app/`.
|
||||||
|
26. Namespace layout (architecture): default `app/` skeleton vs domain/module folders (`app/Domain/**`, modules).
|
||||||
|
- Hint: `ls app/`, look for `Domain/`, `Modules/`, bounded-context folders.
|
||||||
|
27. Enums: backed vs pure, case naming, and where they live.
|
||||||
|
- Hint: `ls app/Enums`. Grep `enum .*: string`, `enum .*: int`.
|
||||||
|
|
||||||
|
## F. Frontend & views
|
||||||
|
|
||||||
|
No Livewire/Inertia/Flux package is installed. This app may be API-only. Confirm from `resources/views` before sweeping, and treat the Livewire/Flux dimensions as not applicable.
|
||||||
|
|
||||||
|
28. Frontend stack: Blade+Livewire vs Inertia (Vue/React/Svelte) vs Blade-only / API + separate SPA.
|
||||||
|
- Hint: `composer.json` + `package.json`. `ls resources/js/pages`, `resources/views`.
|
||||||
|
29. Blade composition: class `<x-*>` components vs anonymous components (`@props`) vs `@include` partials.
|
||||||
|
- Hint: `ls app/View/Components`. Grep `<x-`, `@include` in `resources/views`.
|
||||||
|
32. Localization: short keys (`lang/*/*.php` + `__('messages.welcome')`) vs JSON string keys (`lang/*.json` + `__('Full sentence')`).
|
||||||
|
- Hint: `ls lang`. Grep dotted `__('` vs sentence keys.
|
||||||
|
|
||||||
|
## G. Database & migrations
|
||||||
|
|
||||||
|
33. Foreign keys: `foreignId()->constrained()` vs `foreignIdFor(Model::class)` vs manual `foreign()->references()->on()`.
|
||||||
|
- Hint: grep -- `foreignId(`, `foreignIdFor(`, `->foreign(` in `database/migrations`.
|
||||||
|
34. `down()` methods: real reverse logic vs omitted / one-way migrations.
|
||||||
|
- Hint: grep `function down` vs the migration count.
|
||||||
|
35. Enum storage: DB `enum()` column vs `string()` + PHP-enum cast on the model.
|
||||||
|
- Hint: grep -- `->enum(` in migrations vs string columns cast to enums.
|
||||||
|
36. Transactions: `DB::transaction(fn ...)` closure vs manual `beginTransaction` / `commit` / `rollBack`.
|
||||||
|
- Hint: grep `DB::transaction`, `beginTransaction` in `app/`.
|
||||||
|
37. Idempotent writes: `upsert` / `updateOrCreate` / `firstOrCreate` vs find-then-save.
|
||||||
|
- Hint: grep `upsert(`, `updateOrCreate(`, `firstOrCreate(` in `app/`.
|
||||||
|
|
||||||
|
## H. Testing
|
||||||
|
|
||||||
|
38. Framework: Pest (`it()` / `test()` / `expect()`) vs PHPUnit classes.
|
||||||
|
- Hint: `ls tests/Pest.php`. Grep `it(` / `test(` vs `extends TestCase`.
|
||||||
|
39. DB reset: `RefreshDatabase` vs `DatabaseTruncation` vs `DatabaseMigrations`.
|
||||||
|
- Hint: grep those trait names in `tests/`.
|
||||||
|
40. Fixtures: compare how equivalent test-owned records are created, such as factories vs manual inserts. Track seeders separately for shared reference data because `$this->seed()` commonly and legitimately coexists with factories.
|
||||||
|
- Hint: grep `::factory(` and direct inserts in `tests/`. Separately inspect `$this->seed(` calls and what those seeders provide.
|
||||||
|
41. Collaborator isolation: how the app doubles its own classes, Mockery `mock()` / `spy()` vs real integration. Ignore facade fakes like `Mail::fake()` here. They isolate framework services by default and are not a fork against Mockery.
|
||||||
|
- Hint: grep -- `->mock(`, `->spy(`, `Mockery::` in `tests/`.
|
||||||
|
42. Endpoint assertions: array `assertJson([...])` / `assertJsonFragment` vs fluent `AssertableJson`.
|
||||||
|
- Hint: grep `AssertableJson`, `assertJsonFragment` in `tests/`.
|
||||||
|
|
||||||
|
## I. Responses & API resources
|
||||||
|
|
||||||
|
43. Response shape: API Resource classes vs `response()->json()` vs returning models/arrays directly.
|
||||||
|
- Hint: `ls app/Http/Resources`. Grep -- `JsonResource`, `->json(` in controllers.
|
||||||
|
44. Resource relationship inclusion: `whenLoaded()` guards vs unconditional relationship access. Do not count ordinary scalar attributes as rivals to conditional relationships, and evaluate general `when()` fields separately.
|
||||||
|
- Hint: compare relationship fields using `whenLoaded(` with unconditional relationship property access in `app/Http/Resources`.
|
||||||
|
45. Pagination contracts: within comparable endpoint categories, length-aware `paginate()` vs `simplePaginate()` vs `cursorPaginate()`. These have different totals, navigation, ordering, and performance contracts, so record only a stable path-scoped API policy, never a project-wide majority.
|
||||||
|
- Hint: grep those in `app/`, then group matches by endpoint type and client contract before comparing them.
|
||||||
|
46. Web redirects/URLs: `route('name')` vs `url('/path')` vs `action([...])`.
|
||||||
|
- Hint: grep `route('`, `url('/`, `action([` in `app/Http` and views.
|
||||||
|
|
||||||
|
## J. Strings, collections & dates
|
||||||
|
|
||||||
|
47. Iteration idiom: `collect()->map()->filter()` pipelines vs `array_map` / `foreach`.
|
||||||
|
- Hint: grep -- `collect(`, `->map(` vs `array_map`, `foreach` density in `app/`.
|
||||||
|
48. String API: fluent `Str::of()->...` (Stringable) vs static `Str::` vs native (`trim`, `strtoupper`).
|
||||||
|
- Hint: grep `Str::of(` vs `Str::` vs native string funcs.
|
||||||
|
49. Dates: compare equivalent construction call styles (`now()` / `today()` helpers vs `Carbon::`) separately from the application's mutable/immutable date policy. `Date::use(CarbonImmutable::class)` can make helpers return immutable dates, so those signals are complementary rather than conflicting.
|
||||||
|
- Hint: grep `now(` and `Carbon::` for call style. Separately inspect `CarbonImmutable` and `Date::use` for mutability policy.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
Genuine forks only. Every row survived the "no tool can decide this, and it isn't the default" filter. Give each applicable dimension exactly one verdict: pattern, conflict, default, no-signal, tooling-owned, or already-recorded. The rows tagged (architecture) are where the highest-value rules come from.
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
---
|
||||||
|
name: laravel-best-practices
|
||||||
|
description: "Apply this skill whenever writing, reviewing, or refactoring Laravel PHP code. This includes creating or modifying controllers, models, migrations, form requests, policies, jobs, scheduled commands, service classes, and Eloquent queries. Triggers for N+1 and query performance issues, caching strategies, authorization and security patterns, validation, error handling, queue and job configuration, route definitions, and architectural decisions. Also use for Laravel code reviews and refactoring existing Laravel code to follow best practices. Covers any task involving Laravel backend PHP code patterns."
|
||||||
|
license: MIT
|
||||||
|
metadata:
|
||||||
|
author: laravel
|
||||||
|
---
|
||||||
|
|
||||||
|
# Laravel best practices
|
||||||
|
|
||||||
|
Best practices for Laravel, organized as an index of rule files. Each rule file teaches what to do and why. For exact API syntax, verify with `search-docs`.
|
||||||
|
|
||||||
|
## Consistency first
|
||||||
|
|
||||||
|
Before applying any rule, check what the application already does. Laravel offers several valid approaches. The best choice is the one the codebase already uses, even if another pattern would be better in theory. Inconsistency is worse than a suboptimal pattern.
|
||||||
|
|
||||||
|
Check sibling files and related controllers, models, or tests for established patterns. If one exists, follow it. Don't introduce a second way. These rules are defaults for when no pattern exists yet, not overrides.
|
||||||
|
|
||||||
|
## How to apply
|
||||||
|
|
||||||
|
1. Check the changed files, nearby code, project configuration, and relevant tests for established patterns. Deviate only for a correctness or security defect, and call the deviation out.
|
||||||
|
2. Map every affected concern to the rule index below. Read each mapped rule file before editing. Skip unrelated rule files.
|
||||||
|
3. Make the smallest coherent change. Keep the application's architecture and naming instead of introducing a second pattern for the same job.
|
||||||
|
4. Verify version-sensitive Laravel APIs for the installed version with `search-docs`, or inspect the installed framework when `search-docs` is unavailable.
|
||||||
|
5. Run the narrowest relevant tests first, then the project's formatting and static-analysis checks when the change warrants them.
|
||||||
|
6. Re-read the diff against every mapped rule before finishing.
|
||||||
|
|
||||||
|
## Rule index
|
||||||
|
|
||||||
|
Cross-cutting changes often need more than one rule file.
|
||||||
|
|
||||||
|
| Concern | Read |
|
||||||
|
| --- | --- |
|
||||||
|
| Query count, eager loading, indexes, large datasets | [`rules/db-performance.md`](rules/db-performance.md) |
|
||||||
|
| Subqueries, aggregates, complex ordering and query plans | [`rules/advanced-queries.md`](rules/advanced-queries.md) |
|
||||||
|
| Models, relationships, scopes, casts | [`rules/eloquent.md`](rules/eloquent.md) |
|
||||||
|
| Authentication, authorization, input safety, secrets, uploads | [`rules/security.md`](rules/security.md) |
|
||||||
|
| Form Requests and validation rules | [`rules/validation.md`](rules/validation.md) |
|
||||||
|
| Controllers, route binding, resources, middleware | [`rules/routing.md`](rules/routing.md) |
|
||||||
|
| Schema changes, columns, foreign keys, indexes | [`rules/migrations.md`](rules/migrations.md) |
|
||||||
|
| Jobs, retries, uniqueness, batches, Horizon | [`rules/queue-jobs.md`](rules/queue-jobs.md) |
|
||||||
|
| Cache lifetime, invalidation, locks, memoization | [`rules/caching.md`](rules/caching.md) |
|
||||||
|
| Outbound requests, retries, timeouts, fakes | [`rules/http-client.md`](rules/http-client.md) |
|
||||||
|
| Exceptions, reporting, rendering, log context | [`rules/error-handling.md`](rules/error-handling.md) |
|
||||||
|
| Events and notifications | [`rules/events-notifications.md`](rules/events-notifications.md) |
|
||||||
|
| Mailables and mail assertions | [`rules/mail.md`](rules/mail.md) |
|
||||||
|
| Scheduled tasks and overlap protection | [`rules/scheduling.md`](rules/scheduling.md) |
|
||||||
|
| Collections, lazy iteration, bulk operations | [`rules/collections.md`](rules/collections.md) |
|
||||||
|
| Blade components, attributes, composers | [`rules/blade-views.md`](rules/blade-views.md) |
|
||||||
|
| Environment values and application configuration | [`rules/config.md`](rules/config.md) |
|
||||||
|
| Tests: coverage, factories, fakes, and assertions | the `testing-best-practices` skill |
|
||||||
|
| Naming, helpers, file boundaries, PHP style | [`rules/style.md`](rules/style.md) |
|
||||||
|
| Actions, services, dependencies, application structure | [`rules/architecture.md`](rules/architecture.md) |
|
||||||
|
|
||||||
|
## Decision rules
|
||||||
|
|
||||||
|
- Prefer framework features and existing application abstractions over new helpers or dependencies.
|
||||||
|
- Avoid speculative abstractions. Extract code when it creates a clear domain boundary, removes meaningful duplication, or makes behavior independently testable.
|
||||||
|
- Keep database access out of Blade views and prevent hidden N+1 queries across controllers, resources, jobs, and serialization.
|
||||||
@@ -0,0 +1,106 @@
|
|||||||
|
# Advanced query best practices
|
||||||
|
|
||||||
|
## Select single relationship values with subqueries
|
||||||
|
|
||||||
|
When you need only one value from a has-many relationship, consider a correlated subquery with `addSelect()` instead of loading the entire relationship. The subquery selects the value as part of the main query, without an additional relationship query.
|
||||||
|
|
||||||
|
```php
|
||||||
|
public function scopeWithLastLoginAt($query): void
|
||||||
|
{
|
||||||
|
$query->addSelect([
|
||||||
|
'last_login_at' => Login::select('created_at')
|
||||||
|
->whereColumn('user_id', 'users.id')
|
||||||
|
->latest()
|
||||||
|
->take(1),
|
||||||
|
])->withCasts(['last_login_at' => 'datetime']);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Create dynamic relationships with a subquery foreign key
|
||||||
|
|
||||||
|
The same pattern can select a foreign key and expose the selected model through a `belongsTo` relationship. Eager loading that relationship still runs a separate query, but the pattern avoids loading the full has-many collection.
|
||||||
|
|
||||||
|
```php
|
||||||
|
public function lastLogin(): BelongsTo
|
||||||
|
{
|
||||||
|
return $this->belongsTo(Login::class, 'last_login_id');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function scopeWithLastLogin($query): void
|
||||||
|
{
|
||||||
|
$query->addSelect([
|
||||||
|
'last_login_id' => Login::select('id')
|
||||||
|
->whereColumn('user_id', 'users.id')
|
||||||
|
->latest()
|
||||||
|
->take(1),
|
||||||
|
])->with('lastLogin');
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Combine related counts with conditional aggregates
|
||||||
|
|
||||||
|
Use conditional aggregates to combine several counts over the same filtered data set into one query. Use `toBase()` when you need only scalar values and model hydration adds nothing. Confirm the expression syntax against the application's database engine.
|
||||||
|
|
||||||
|
```php
|
||||||
|
$statuses = Feature::toBase()
|
||||||
|
->selectRaw("count(case when status = 'Requested' then 1 end) as requested")
|
||||||
|
->selectRaw("count(case when status = 'Planned' then 1 end) as planned")
|
||||||
|
->selectRaw("count(case when status = 'Completed' then 1 end) as completed")
|
||||||
|
->first();
|
||||||
|
```
|
||||||
|
|
||||||
|
## Reuse loaded parent models with `setRelation()`
|
||||||
|
|
||||||
|
When a parent and its children are already loaded and code also accesses `$child->parent`, set the inverse relationship to the existing parent instance. Setting the inverse relationship avoids an extra lazy-loading query for each child.
|
||||||
|
|
||||||
|
```php
|
||||||
|
$feature->load('comments.user');
|
||||||
|
$feature->comments->each->setRelation('feature', $feature);
|
||||||
|
```
|
||||||
|
|
||||||
|
## Compare `whereHas()` with an `IN` subquery
|
||||||
|
|
||||||
|
`whereHas()` typically produces an `EXISTS` subquery, while `whereIn()` can express the same filter with an `IN` subquery. Either form can be faster, depending on the database engine, indexes, cardinality, and query plan. Measure both forms with representative data. Neither subquery loads its result set into PHP memory.
|
||||||
|
|
||||||
|
Option using `EXISTS`:
|
||||||
|
|
||||||
|
```php
|
||||||
|
$query->whereHas('company', fn ($q) => $q->where('name', 'like', $term));
|
||||||
|
```
|
||||||
|
|
||||||
|
Option using `IN`:
|
||||||
|
|
||||||
|
```php
|
||||||
|
$query->whereIn('company_id', Company::where('name', 'like', $term)->select('id'));
|
||||||
|
```
|
||||||
|
|
||||||
|
## Measure two simple queries against one complex query
|
||||||
|
|
||||||
|
Two targeted queries can outperform one complex correlated subquery or join when the first query is highly selective. They also add a database round trip, can transfer a large identifier list, and do not provide a single-query consistency snapshot. Decide from query plans and production-like measurements.
|
||||||
|
|
||||||
|
## Design composite indexes for the query
|
||||||
|
|
||||||
|
For common multi-column sorts, consider a composite index whose column order supports the query's filters and ordering. Database engines may combine indexes or choose an explicit sort, so matching the `ORDER BY` list alone does not guarantee that the engine uses the index. Verify the query plan.
|
||||||
|
|
||||||
|
```php
|
||||||
|
// Migration
|
||||||
|
$table->index(['last_name', 'first_name']);
|
||||||
|
|
||||||
|
// Query that this index may support
|
||||||
|
User::query()->orderBy('last_name')->orderBy('first_name')->paginate();
|
||||||
|
```
|
||||||
|
|
||||||
|
## Consider a correlated subquery for has-many ordering
|
||||||
|
|
||||||
|
When sorting by one value from a has-many relationship, a direct join can duplicate parent rows unless it first reduces the related table to one row per parent. A correlated subquery in `orderBy()` is often simpler, but its performance depends on the query plan and supporting indexes.
|
||||||
|
|
||||||
|
```php
|
||||||
|
public function scopeOrderByLastLogin($query): void
|
||||||
|
{
|
||||||
|
$query->orderByDesc(Login::select('created_at')
|
||||||
|
->whereColumn('user_id', 'users.id')
|
||||||
|
->latest()
|
||||||
|
->take(1)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
```
|
||||||
@@ -0,0 +1,219 @@
|
|||||||
|
# Architecture best practices
|
||||||
|
|
||||||
|
## Extract focused business operations
|
||||||
|
|
||||||
|
Extract a discrete business operation into an action class when doing so makes the operation easier to reuse or test. An action class has no special meaning to Laravel. Follow the project's naming and invocation conventions.
|
||||||
|
|
||||||
|
```php
|
||||||
|
class CreateOrderAction
|
||||||
|
{
|
||||||
|
public function __construct(private InventoryService $inventory) {}
|
||||||
|
|
||||||
|
public function handle(array $data): Order
|
||||||
|
{
|
||||||
|
$order = Order::create($data);
|
||||||
|
$this->inventory->reserve($order);
|
||||||
|
|
||||||
|
return $order;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Inject required dependencies
|
||||||
|
|
||||||
|
Prefer constructor injection for dependencies required throughout an object's lifetime. Use method injection for a dependency that one controller action, listener, job handler, or other container-invoked method needs. Avoid `app()` and `resolve()` when normal injection can make a dependency explicit.
|
||||||
|
|
||||||
|
Hidden dependency:
|
||||||
|
|
||||||
|
```php
|
||||||
|
class OrderController extends Controller
|
||||||
|
{
|
||||||
|
public function store(StoreOrderRequest $request)
|
||||||
|
{
|
||||||
|
$service = app(OrderService::class);
|
||||||
|
|
||||||
|
return $service->create($request->validated());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Injected dependency:
|
||||||
|
|
||||||
|
```php
|
||||||
|
class OrderController extends Controller
|
||||||
|
{
|
||||||
|
public function store(StoreOrderRequest $request, OrderService $service)
|
||||||
|
{
|
||||||
|
return $service->create($request->validated());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Depend on contracts at boundaries
|
||||||
|
|
||||||
|
Depend on contracts at system boundaries, such as payment gateways, notification channels, and external services, when testability or interchangeable implementations justify the abstraction.
|
||||||
|
|
||||||
|
Concrete boundary dependency:
|
||||||
|
|
||||||
|
```php
|
||||||
|
class OrderService
|
||||||
|
{
|
||||||
|
public function __construct(private StripeGateway $gateway) {}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Contract boundary dependency:
|
||||||
|
|
||||||
|
```php
|
||||||
|
interface PaymentGateway
|
||||||
|
{
|
||||||
|
public function charge(int $amount, string $customerId): PaymentResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
class OrderService
|
||||||
|
{
|
||||||
|
public function __construct(private PaymentGateway $gateway) {}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Bind in a service provider:
|
||||||
|
|
||||||
|
```php
|
||||||
|
$this->app->bind(PaymentGateway::class, StripeGateway::class);
|
||||||
|
```
|
||||||
|
|
||||||
|
## Specify a deterministic sort order
|
||||||
|
|
||||||
|
Without an explicit `ORDER BY`, row order is undefined. Choose an order that matches the feature, and add a unique tie-breaker when stable pagination matters.
|
||||||
|
|
||||||
|
Unspecified order:
|
||||||
|
|
||||||
|
```php
|
||||||
|
$posts = Post::paginate();
|
||||||
|
```
|
||||||
|
|
||||||
|
Newest first with a stable tie-breaker:
|
||||||
|
|
||||||
|
```php
|
||||||
|
$posts = Post::query()
|
||||||
|
->orderByDesc('created_at')
|
||||||
|
->orderByDesc('id')
|
||||||
|
->paginate();
|
||||||
|
```
|
||||||
|
|
||||||
|
## Use atomic locks for race conditions
|
||||||
|
|
||||||
|
Use a lock when concurrent processes must run one at a time. `Cache::lock()` provides an atomic lock when the configured cache store supports locks. `lockForUpdate()` locks selected database rows and must run inside a database transaction. These mechanisms solve different coordination problems. Set the lease (`10` below) longer than the callback can ever run. Once the lease expires, another process can acquire the lock while the first process is still working.
|
||||||
|
|
||||||
|
```php
|
||||||
|
Cache::lock('order-processing-'.$order->id, 10)->block(5, function () use ($order) {
|
||||||
|
$order->process();
|
||||||
|
});
|
||||||
|
|
||||||
|
// Or at query level, inside a transaction
|
||||||
|
DB::transaction(function () use ($id) {
|
||||||
|
$product = Product::where('id', $id)->lockForUpdate()->first();
|
||||||
|
|
||||||
|
// Read and update the product while the database lock is held.
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
## Use `mb_*` string functions
|
||||||
|
|
||||||
|
When no Laravel helper exists, prefer multibyte-aware functions such as `mb_strlen()` and `mb_strtolower()` for UTF-8 text. For example, `strlen()` counts bytes, while `strtolower()` is not multibyte-aware.
|
||||||
|
|
||||||
|
Incorrect:
|
||||||
|
|
||||||
|
```php
|
||||||
|
strlen('José'); // 5 bytes, not 4 characters
|
||||||
|
strtolower('MÜNCHEN'); // Does not lowercase Ü
|
||||||
|
```
|
||||||
|
|
||||||
|
Correct:
|
||||||
|
|
||||||
|
```php
|
||||||
|
mb_strlen('José'); // 4 characters
|
||||||
|
mb_strtolower('MÜNCHEN'); // 'münchen'
|
||||||
|
|
||||||
|
// Prefer Laravel's Str helpers when available
|
||||||
|
Str::length('José'); // 4
|
||||||
|
Str::lower('MÜNCHEN'); // 'münchen'
|
||||||
|
```
|
||||||
|
|
||||||
|
## Use `defer()` for post-response work
|
||||||
|
|
||||||
|
For lightweight work that does not need retries or crash durability, consider `defer()` instead of dispatching a job. During an HTTP request, the callback normally runs after Laravel sends the response, but it still runs in the same PHP process.
|
||||||
|
|
||||||
|
Queued and durable:
|
||||||
|
|
||||||
|
```php
|
||||||
|
dispatch(new LogPageView($page));
|
||||||
|
```
|
||||||
|
|
||||||
|
Deferred in the current process:
|
||||||
|
|
||||||
|
```php
|
||||||
|
defer(fn () => PageView::create(['page_id' => $page->id, 'user_id' => auth()->id()]));
|
||||||
|
```
|
||||||
|
|
||||||
|
Use a queued job when the work needs retries, queue controls, or durability across process failures.
|
||||||
|
|
||||||
|
## Use `Context` for request-scoped data
|
||||||
|
|
||||||
|
The `Context` facade makes contextual data available across the current execution lifecycle without manually passing arguments through every layer.
|
||||||
|
|
||||||
|
```php
|
||||||
|
// In middleware
|
||||||
|
Context::add('tenant_id', $request->header('X-Tenant-ID'));
|
||||||
|
|
||||||
|
// Later in the same execution lifecycle
|
||||||
|
$tenantId = Context::get('tenant_id');
|
||||||
|
```
|
||||||
|
|
||||||
|
Laravel adds visible context to log context. It also captures both visible and hidden context and restores them for queued jobs. Use `Context::addHidden()` for data that should propagate to queued jobs without appearing in logs. Do not place secrets in context unless you intend that propagation.
|
||||||
|
|
||||||
|
## Use `Concurrency::run()` for parallel execution
|
||||||
|
|
||||||
|
Run independent operations concurrently through Laravel's configured concurrency driver.
|
||||||
|
|
||||||
|
```php
|
||||||
|
use Illuminate\Support\Facades\Concurrency;
|
||||||
|
|
||||||
|
[$users, $orders] = Concurrency::run([
|
||||||
|
fn () => User::count(),
|
||||||
|
fn () => Order::where('status', 'pending')->count(),
|
||||||
|
]);
|
||||||
|
```
|
||||||
|
|
||||||
|
With a process-based driver, each closure runs in a separate PHP process that boots the application. Use concurrency when independent database queries, HTTP client calls, or computations benefit enough to offset process and serialization overhead. The `sync` driver runs closures sequentially and is mainly useful during testing.
|
||||||
|
|
||||||
|
## Follow framework conventions
|
||||||
|
|
||||||
|
Follow Laravel conventions unless the domain or an existing schema requires an override.
|
||||||
|
|
||||||
|
Customized schema:
|
||||||
|
|
||||||
|
```php
|
||||||
|
class Customer extends Model
|
||||||
|
{
|
||||||
|
protected $table = 'Customer';
|
||||||
|
protected $primaryKey = 'customer_id';
|
||||||
|
|
||||||
|
public function roles(): BelongsToMany
|
||||||
|
{
|
||||||
|
return $this->belongsToMany(Role::class, 'role_customer', 'customer_id', 'role_id');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Conventional schema:
|
||||||
|
|
||||||
|
```php
|
||||||
|
class Customer extends Model
|
||||||
|
{
|
||||||
|
public function roles(): BelongsToMany
|
||||||
|
{
|
||||||
|
return $this->belongsToMany(Role::class);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
# Blade and view best practices
|
||||||
|
|
||||||
|
## Use `$attributes->merge()` in component templates
|
||||||
|
|
||||||
|
Use the component attribute bag so callers can add attributes. `merge()` combines default attributes with caller-provided values. Class values receive special merging behavior.
|
||||||
|
|
||||||
|
```blade
|
||||||
|
<div {{ $attributes->merge(['class' => 'alert alert-'.$type]) }}>
|
||||||
|
{{ $message }}
|
||||||
|
</div>
|
||||||
|
```
|
||||||
|
|
||||||
|
## Use `@pushOnce` for per-component scripts
|
||||||
|
|
||||||
|
If a component renders repeatedly, `@push` adds its script on every render. Use a consistently named `@pushOnce` block to add that content once per rendered response.
|
||||||
|
|
||||||
|
## Prefer components for explicit interfaces
|
||||||
|
|
||||||
|
Use a Blade component when a reusable interface benefits from explicit props, an attribute bag, or slots. An include still suits a small partial that intentionally uses the current view data. Pass an explicit data array when implicit variable sharing would hide the partial's dependencies.
|
||||||
|
|
||||||
|
## Share compatible view data with a view composer
|
||||||
|
|
||||||
|
Use a view composer to centralize the data that one or more named Blade views need every time Laravel renders them. Keep the composer compatible with every view it targets, and avoid broad wildcards when views require different data shapes. A view composer runs when Laravel renders the matching view. It does not supply data to JSON, streamed, or other non-view responses.
|
||||||
|
|
||||||
|
## Return Blade fragments for partial rendering
|
||||||
|
|
||||||
|
A route can return either a full view or a named fragment for clients such as htmx or Turbo.
|
||||||
|
|
||||||
|
```php
|
||||||
|
return view('dashboard', compact('users'))
|
||||||
|
->fragmentIf($request->hasHeader('HX-Request'), 'user-list');
|
||||||
|
```
|
||||||
|
|
||||||
|
## Share parent component props with `@aware`
|
||||||
|
|
||||||
|
Use `@aware` when a nested component needs a prop explicitly passed to an ancestor component. `@aware` does not expose an ancestor's default prop value unless that value was passed through the attribute bag.
|
||||||
@@ -0,0 +1,100 @@
|
|||||||
|
# Caching best practices
|
||||||
|
|
||||||
|
## Use `Cache::remember()` for cache-aside reads
|
||||||
|
|
||||||
|
`Cache::remember()` implements a cache-aside read without a separate truthiness check. It does not prevent concurrent requests from computing the same missing value. When you must prevent duplicate computation, use an atomic lock.
|
||||||
|
|
||||||
|
The manual version below treats valid falsy values, such as `false` or `0`, as cache misses.
|
||||||
|
|
||||||
|
Incorrect:
|
||||||
|
|
||||||
|
```php
|
||||||
|
$val = Cache::get('stats');
|
||||||
|
if (! $val) {
|
||||||
|
$val = $this->computeStats();
|
||||||
|
Cache::put('stats', $val, 60);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Correct:
|
||||||
|
|
||||||
|
```php
|
||||||
|
$val = Cache::remember('stats', 60, fn () => $this->computeStats());
|
||||||
|
```
|
||||||
|
|
||||||
|
## Consider `Cache::flexible()` for stale-while-revalidate
|
||||||
|
|
||||||
|
For frequently read keys, `Cache::flexible()` can serve stale data during a defined stale period and register a deferred refresh. During an HTTP request, that refresh normally runs after the response. The refresh is not a durable background job. After the stale period ends, the request recomputes the value synchronously.
|
||||||
|
|
||||||
|
Synchronous expiration:
|
||||||
|
|
||||||
|
```php
|
||||||
|
Cache::remember('users', 300, fn () => User::all());
|
||||||
|
```
|
||||||
|
|
||||||
|
Stale-while-revalidate tradeoff:
|
||||||
|
|
||||||
|
```php
|
||||||
|
Cache::flexible('users', [300, 600], fn () => User::all());
|
||||||
|
```
|
||||||
|
|
||||||
|
In this example, the value is fresh for five minutes. Laravel may serve the stale value until ten minutes after it was cached.
|
||||||
|
|
||||||
|
## Use `Cache::memo()` to avoid redundant hits within an execution
|
||||||
|
|
||||||
|
When code reads the same cache key repeatedly during one request or job, `memo()` decorates a cache store and keeps resolved values in memory for that execution.
|
||||||
|
|
||||||
|
```php
|
||||||
|
$settings = Cache::memo()->get('settings');
|
||||||
|
```
|
||||||
|
|
||||||
|
Repeated reads through the same memoized store avoid additional store lookups. Writes through the memoized store update or invalidate its in-memory values as appropriate.
|
||||||
|
|
||||||
|
## Use cache tags to invalidate related groups
|
||||||
|
|
||||||
|
Tags group related entries for invalidation without tracking each key. The `file`, `dynamodb`, and `database` drivers do not support cache tags. Confirm that a store supports tags before you choose it.
|
||||||
|
|
||||||
|
```php
|
||||||
|
Cache::tags(['user-1'])->flush();
|
||||||
|
```
|
||||||
|
|
||||||
|
## Use `Cache::add()` for atomic conditional writes
|
||||||
|
|
||||||
|
`add()` atomically writes a value only when the key does not already exist.
|
||||||
|
|
||||||
|
Incorrect:
|
||||||
|
|
||||||
|
```php
|
||||||
|
if (! Cache::has('lock')) {
|
||||||
|
Cache::put('lock', true, 10);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Correct:
|
||||||
|
|
||||||
|
```php
|
||||||
|
Cache::add('lock', true, 10);
|
||||||
|
```
|
||||||
|
|
||||||
|
When you need lock ownership and safe release, use `Cache::lock()` instead of an ordinary cache key.
|
||||||
|
|
||||||
|
## Use `once()` for in-process memoization
|
||||||
|
|
||||||
|
`once()` memoizes a callback's return value for the current request or job. Calls made from an object instance are scoped to that instance. Unlike `Cache::memo()`, `once()` does not read from an external cache store.
|
||||||
|
|
||||||
|
```php
|
||||||
|
public function roles(): Collection
|
||||||
|
{
|
||||||
|
return once(fn () => $this->loadRoles());
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Repeated calls return the memoized result without rerunning the callback. Use `once()` for repeated computation within one execution. Use `Cache::memo()` to memoize access to an underlying store that can also persist values across executions.
|
||||||
|
|
||||||
|
## Configure failover cache stores in production
|
||||||
|
|
||||||
|
The failover driver tries each configured store in order when a store operation throws an exception. It does not consult later stores for an ordinary cache miss, and it does not replicate data between stores.
|
||||||
|
|
||||||
|
```php
|
||||||
|
'failover' => ['driver' => 'failover', 'stores' => ['redis', 'database']],
|
||||||
|
```
|
||||||
@@ -0,0 +1,72 @@
|
|||||||
|
# Collection best practices
|
||||||
|
|
||||||
|
## Use higher-order messages for simple operations
|
||||||
|
|
||||||
|
Explicit closure:
|
||||||
|
|
||||||
|
```php
|
||||||
|
$users->each(function (User $user) {
|
||||||
|
$user->markAsVip();
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
Concise equivalent:
|
||||||
|
|
||||||
|
```php
|
||||||
|
$users->each->markAsVip();
|
||||||
|
```
|
||||||
|
|
||||||
|
Higher-order messages work with supported collection methods such as `each`, `map`, `filter`, and `sum`. Use an explicit closure when arguments or nontrivial logic would be clearer.
|
||||||
|
|
||||||
|
## Choose between `cursor()` and `lazy()`
|
||||||
|
|
||||||
|
`cursor()` executes one query and hydrates one model at a time, but it cannot eager load relationships. The database driver's result buffering can still use a lot of memory for very large results. Use it for low-memory, attribute-only iteration when one long-running query is acceptable.
|
||||||
|
|
||||||
|
`lazy()` executes multiple chunked queries and returns a flat `LazyCollection`. It supports eager loading relationships for each chunk and avoids holding one database cursor open for the entire iteration.
|
||||||
|
|
||||||
|
With relationships:
|
||||||
|
|
||||||
|
```php
|
||||||
|
User::with('roles')->lazy()->each(function (User $user) {
|
||||||
|
// The roles for this chunk have been eager loaded.
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
Without relationships:
|
||||||
|
|
||||||
|
```php
|
||||||
|
User::cursor()->each(function (User $user) {
|
||||||
|
// Process model attributes.
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
## Use `lazyById()` when updating records while iterating
|
||||||
|
|
||||||
|
`lazy()` uses offset pagination, so updating a column that affects the query can shift rows and make the iteration skip records or process them twice. `lazyById()` paginates by a monotonic key and is safer when you update other columns during iteration. Do not change the pagination key itself while iterating.
|
||||||
|
|
||||||
|
## Use `toQuery()` for bulk operations on collections
|
||||||
|
|
||||||
|
Use `toQuery()` to build a query from the models in an Eloquent collection instead of manually constructing a `whereIn` clause.
|
||||||
|
|
||||||
|
Manual query:
|
||||||
|
|
||||||
|
```php
|
||||||
|
User::whereIn('id', $users->modelKeys())->update(['active' => false]);
|
||||||
|
```
|
||||||
|
|
||||||
|
Collection query:
|
||||||
|
|
||||||
|
```php
|
||||||
|
$users->toQuery()->update(['active' => false]);
|
||||||
|
```
|
||||||
|
|
||||||
|
`toQuery()` requires a non-empty Eloquent collection whose models are of the same type. Like other bulk Eloquent updates, it does not dispatch per-model update events, so use it only when you don't need those events.
|
||||||
|
|
||||||
|
## Use `#[CollectedBy]` for custom collection classes
|
||||||
|
|
||||||
|
The `#[CollectedBy]` attribute declares the custom collection class without requiring a `newCollection()` override.
|
||||||
|
|
||||||
|
```php
|
||||||
|
#[CollectedBy(UserCollection::class)]
|
||||||
|
class User extends Model {}
|
||||||
|
```
|
||||||
@@ -0,0 +1,85 @@
|
|||||||
|
# Configuration best practices
|
||||||
|
|
||||||
|
## Read environment variables in configuration files
|
||||||
|
|
||||||
|
Call `env()` only from configuration files. After you cache the configuration, Laravel does not load the application's `.env` file, so read configuration values in application code through `config()`.
|
||||||
|
|
||||||
|
Incorrect:
|
||||||
|
|
||||||
|
```php
|
||||||
|
$key = env('API_KEY');
|
||||||
|
```
|
||||||
|
|
||||||
|
Correct:
|
||||||
|
|
||||||
|
```php
|
||||||
|
// config/services.php
|
||||||
|
return [
|
||||||
|
'key' => env('API_KEY'),
|
||||||
|
];
|
||||||
|
|
||||||
|
// Application code
|
||||||
|
$key = config('services.key');
|
||||||
|
```
|
||||||
|
|
||||||
|
## Protect production secrets
|
||||||
|
|
||||||
|
Do not commit plaintext production secrets. Laravel can encrypt an environment file so you can store the encrypted file safely. Deployment platforms can also supply secrets through their native secret stores.
|
||||||
|
|
||||||
|
Incorrect:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# A plaintext .env file committed to the repository
|
||||||
|
STRIPE_SECRET=<your-stripe-secret>
|
||||||
|
AWS_SECRET_ACCESS_KEY=<your-aws-secret>
|
||||||
|
```
|
||||||
|
|
||||||
|
Encrypted environment file:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
php artisan env:encrypt --env=production --readable
|
||||||
|
php artisan env:decrypt --env=production
|
||||||
|
```
|
||||||
|
|
||||||
|
For hosted deployments, consider the platform's native secret store, such as AWS Secrets Manager or Vault, and inject secrets at runtime.
|
||||||
|
|
||||||
|
## Use `App::environment()` for environment checks
|
||||||
|
|
||||||
|
Incorrect:
|
||||||
|
|
||||||
|
```php
|
||||||
|
if (env('APP_ENV') === 'production') {
|
||||||
|
// ...
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Correct:
|
||||||
|
|
||||||
|
```php
|
||||||
|
if (app()->isProduction()) {
|
||||||
|
// ...
|
||||||
|
}
|
||||||
|
|
||||||
|
if (App::environment('production')) {
|
||||||
|
// ...
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Name repeated domain values
|
||||||
|
|
||||||
|
Use an enum or class constant when a domain value is repeated or represents a constrained set. A one-off string literal does not always need a named constant.
|
||||||
|
|
||||||
|
```php
|
||||||
|
// Repeated literal
|
||||||
|
return $this->type === 'normal';
|
||||||
|
|
||||||
|
// Named domain value
|
||||||
|
return $this->type === self::TYPE_NORMAL;
|
||||||
|
```
|
||||||
|
|
||||||
|
If the application supports localization, put user-facing strings in language files and retrieve them with `__()`. Simple literals are reasonable for applications that intentionally do not support multiple languages.
|
||||||
|
|
||||||
|
```php
|
||||||
|
// In a localized application
|
||||||
|
return back()->with('message', __('app.article_added'));
|
||||||
|
```
|
||||||
@@ -0,0 +1,189 @@
|
|||||||
|
# Database performance best practices
|
||||||
|
|
||||||
|
## Eager load relationships before iterating
|
||||||
|
|
||||||
|
When code accesses a relationship on many models, eager load the relationship with `with()`. Eager loading avoids the N+1 query pattern: one initial query plus one relationship query per model. Lazy loading is reasonable when the code may not need the relationship or when only one model is involved.
|
||||||
|
|
||||||
|
Lazy-loaded version:
|
||||||
|
|
||||||
|
```php
|
||||||
|
$posts = Post::all();
|
||||||
|
foreach ($posts as $post) {
|
||||||
|
echo $post->author->name;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Eager-loaded version:
|
||||||
|
|
||||||
|
```php
|
||||||
|
$posts = Post::with('author')->get();
|
||||||
|
foreach ($posts as $post) {
|
||||||
|
echo $post->author->name;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Constrain an eager load when the code does not need the large columns. Include the related model's primary key and every column Eloquent needs to match the relationship. In this example, `users.id` and `posts.user_id` match posts to users, and selecting `posts.id` keeps each related model's primary key:
|
||||||
|
|
||||||
|
```php
|
||||||
|
$users = User::with(['posts' => function ($query) {
|
||||||
|
$query->select('id', 'user_id', 'title')
|
||||||
|
->where('published', true)
|
||||||
|
->latest()
|
||||||
|
->limit(10);
|
||||||
|
}])->get();
|
||||||
|
```
|
||||||
|
|
||||||
|
## Prevent lazy loading in development
|
||||||
|
|
||||||
|
Enable lazy-loading prevention in `AppServiceProvider::boot()` to catch N+1 queries during development.
|
||||||
|
|
||||||
|
```php
|
||||||
|
public function boot(): void
|
||||||
|
{
|
||||||
|
Model::preventLazyLoading(! app()->isProduction());
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
With prevention enabled, accessing an unloaded relationship throws a `LazyLoadingViolationException` by default. To customize violation handling, use `handleLazyLoadingViolationUsing()`.
|
||||||
|
|
||||||
|
## Select only the columns you need
|
||||||
|
|
||||||
|
When omitting large text, binary, or JSON columns gives a meaningful benefit, select only the columns the operation needs.
|
||||||
|
|
||||||
|
All columns:
|
||||||
|
|
||||||
|
```php
|
||||||
|
$posts = Post::with('author')->get();
|
||||||
|
```
|
||||||
|
|
||||||
|
Selected columns:
|
||||||
|
|
||||||
|
```php
|
||||||
|
$posts = Post::select('id', 'title', 'user_id', 'created_at')
|
||||||
|
->with(['author:id,name,avatar'])
|
||||||
|
->get();
|
||||||
|
```
|
||||||
|
|
||||||
|
When you limit the selected columns, keep every key Eloquent needs for matching. A `belongsTo` relationship needs its foreign key on the parent query and the owner's key on the related query. A `hasMany` relationship needs the parent's local key and the related model's foreign key.
|
||||||
|
|
||||||
|
## Process large data sets incrementally
|
||||||
|
|
||||||
|
When loading the entire result set would exceed the application's practical memory budget, use chunking or lazy iteration.
|
||||||
|
|
||||||
|
Loads the complete result set:
|
||||||
|
|
||||||
|
```php
|
||||||
|
$users = User::all();
|
||||||
|
foreach ($users as $user) {
|
||||||
|
$user->notify(new WeeklyDigest);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Processes bounded chunks:
|
||||||
|
|
||||||
|
```php
|
||||||
|
User::where('subscribed', true)->chunk(200, function ($users) {
|
||||||
|
foreach ($users as $user) {
|
||||||
|
$user->notify(new WeeklyDigest);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
Use `chunkById()` when updates can change which rows match the query. Standard `chunk()` uses offset pagination, so result positions can shift as rows change:
|
||||||
|
|
||||||
|
```php
|
||||||
|
User::where('active', false)->chunkById(200, function ($users) {
|
||||||
|
$users->each->delete();
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
For read-only iteration that uses only model attributes, `cursor()` runs one query and hydrates one model at a time. Some database drivers still buffer the raw results. Use `lazy()` when you need to eager load relationships in chunks. Use `lazyById()` or `chunkById()` when updates can change which rows match the query. See the collection rules for detailed tradeoffs.
|
||||||
|
|
||||||
|
## Add indexes for measured query patterns
|
||||||
|
|
||||||
|
Design indexes around frequent, performance-sensitive query patterns. A column's presence in `WHERE`, `ORDER BY`, `JOIN`, or `GROUP BY` does not by itself justify an index. Selectivity, write cost, existing indexes, and the database query plan all matter.
|
||||||
|
|
||||||
|
Schema without an application-specific query index:
|
||||||
|
|
||||||
|
```php
|
||||||
|
Schema::create('orders', function (Blueprint $table) {
|
||||||
|
$table->id();
|
||||||
|
$table->foreignId('user_id')->constrained();
|
||||||
|
$table->string('status');
|
||||||
|
$table->timestamps();
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
Schema optimized for `WHERE status = ? ORDER BY created_at`:
|
||||||
|
|
||||||
|
```php
|
||||||
|
Schema::create('orders', function (Blueprint $table) {
|
||||||
|
$table->id();
|
||||||
|
$table->foreignId('user_id')->constrained();
|
||||||
|
$table->string('status');
|
||||||
|
$table->timestamps();
|
||||||
|
$table->index(['status', 'created_at']);
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
Use production-like data and the database's query-plan tools to confirm the column order of a composite index and whether the index helps. Before you add an index for a foreign key, check whether the database already created one.
|
||||||
|
|
||||||
|
## Count relationships without loading them
|
||||||
|
|
||||||
|
Use `withCount()` when you need only the relationship counts. Loading and hydrating every related model wastes memory.
|
||||||
|
|
||||||
|
Loads related models:
|
||||||
|
|
||||||
|
```php
|
||||||
|
$posts = Post::all();
|
||||||
|
foreach ($posts as $post) {
|
||||||
|
echo $post->comments->count();
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Selects relationship counts:
|
||||||
|
|
||||||
|
```php
|
||||||
|
$posts = Post::withCount('comments')->get();
|
||||||
|
foreach ($posts as $post) {
|
||||||
|
echo $post->comments_count;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Conditional counting:
|
||||||
|
|
||||||
|
```php
|
||||||
|
$posts = Post::withCount([
|
||||||
|
'comments',
|
||||||
|
'comments as approved_comments_count' => function ($query) {
|
||||||
|
$query->where('approved', true);
|
||||||
|
},
|
||||||
|
])->get();
|
||||||
|
```
|
||||||
|
|
||||||
|
## Keep queries out of Blade templates
|
||||||
|
|
||||||
|
Prepare data before rendering a Blade template, for example in a controller, a query service, or a view composer. Queries outside the template stay visible and testable.
|
||||||
|
|
||||||
|
Query in the template:
|
||||||
|
|
||||||
|
```blade
|
||||||
|
@foreach (User::all() as $user)
|
||||||
|
{{ $user->profile->name }}
|
||||||
|
@endforeach
|
||||||
|
```
|
||||||
|
|
||||||
|
Data prepared before rendering:
|
||||||
|
|
||||||
|
```php
|
||||||
|
// Controller
|
||||||
|
$users = User::with('profile')->get();
|
||||||
|
|
||||||
|
return view('users.index', compact('users'));
|
||||||
|
```
|
||||||
|
|
||||||
|
```blade
|
||||||
|
@foreach ($users as $user)
|
||||||
|
{{ $user->profile->name }}
|
||||||
|
@endforeach
|
||||||
|
```
|
||||||
@@ -0,0 +1,158 @@
|
|||||||
|
# Eloquent best practices
|
||||||
|
|
||||||
|
## Define precise relationship types
|
||||||
|
|
||||||
|
Define the relationship that matches the database association, and declare its concrete return type.
|
||||||
|
|
||||||
|
```php
|
||||||
|
public function comments(): HasMany
|
||||||
|
{
|
||||||
|
return $this->hasMany(Comment::class);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function author(): BelongsTo
|
||||||
|
{
|
||||||
|
return $this->belongsTo(User::class, 'user_id');
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Use local scopes for reusable queries
|
||||||
|
|
||||||
|
Extract reusable query constraints into local scopes to avoid duplication.
|
||||||
|
|
||||||
|
Duplicated constraints:
|
||||||
|
|
||||||
|
```php
|
||||||
|
$active = User::where('verified', true)->whereNotNull('activated_at')->get();
|
||||||
|
$articles = Article::whereHas('user', function ($q) {
|
||||||
|
$q->where('verified', true)->whereNotNull('activated_at');
|
||||||
|
})->get();
|
||||||
|
```
|
||||||
|
|
||||||
|
Reusable local scope:
|
||||||
|
|
||||||
|
```php
|
||||||
|
#[Scope]
|
||||||
|
protected function active(Builder $query): Builder
|
||||||
|
{
|
||||||
|
return $query->where('verified', true)->whereNotNull('activated_at');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Usage
|
||||||
|
$active = User::active()->get();
|
||||||
|
$articles = Article::whereHas('user', fn ($q) => $q->active())->get();
|
||||||
|
```
|
||||||
|
|
||||||
|
## Apply global scopes sparingly
|
||||||
|
|
||||||
|
A global scope silently modifies every query on the model, so queries become hard to debug. Prefer local scopes, and reserve global scopes for universal constraints such as soft deletes or multi-tenancy.
|
||||||
|
|
||||||
|
Global scope tradeoff:
|
||||||
|
|
||||||
|
```php
|
||||||
|
class PublishedScope implements Scope
|
||||||
|
{
|
||||||
|
public function apply(Builder $builder, Model $model): void
|
||||||
|
{
|
||||||
|
$builder->where('published', true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Admin panels, reports, and jobs now omit drafts unless the scope is removed.
|
||||||
|
```
|
||||||
|
|
||||||
|
Explicit local scope:
|
||||||
|
|
||||||
|
```php
|
||||||
|
#[Scope]
|
||||||
|
protected function published(Builder $query): Builder
|
||||||
|
{
|
||||||
|
return $query->where('published', true);
|
||||||
|
}
|
||||||
|
|
||||||
|
Post::published()->paginate(); // Explicit
|
||||||
|
Post::paginate(); // Admin sees all
|
||||||
|
```
|
||||||
|
|
||||||
|
## Define attribute casts
|
||||||
|
|
||||||
|
Use the `casts()` method for automatic type conversion. If the project convention is the `$casts` property, follow that convention.
|
||||||
|
|
||||||
|
```php
|
||||||
|
protected function casts(): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
'is_active' => 'boolean',
|
||||||
|
'metadata' => 'array',
|
||||||
|
'total' => 'decimal:2',
|
||||||
|
];
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Cast date and time attributes
|
||||||
|
|
||||||
|
Cast a date or timestamp attribute when application code should treat it as a Carbon instance. Eloquent already casts the conventional `created_at` and `updated_at` timestamps.
|
||||||
|
|
||||||
|
Manual parsing in the template:
|
||||||
|
|
||||||
|
```blade
|
||||||
|
{{ Carbon::parse($order->ordered_at)->toDateString() }}
|
||||||
|
```
|
||||||
|
|
||||||
|
Model cast:
|
||||||
|
|
||||||
|
```php
|
||||||
|
protected function casts(): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
'ordered_at' => 'datetime',
|
||||||
|
];
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
```blade
|
||||||
|
{{ $order->ordered_at->toDateString() }}
|
||||||
|
{{ $order->ordered_at->format('m-d') }}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Use `whereBelongsTo()` for relationship queries
|
||||||
|
|
||||||
|
`whereBelongsTo()` expresses the relationship constraint without naming its foreign key.
|
||||||
|
|
||||||
|
Foreign key constraint:
|
||||||
|
|
||||||
|
```php
|
||||||
|
Post::where('user_id', $user->id)->get();
|
||||||
|
```
|
||||||
|
|
||||||
|
Relationship-aware constraint:
|
||||||
|
|
||||||
|
```php
|
||||||
|
Post::whereBelongsTo($user)->get();
|
||||||
|
Post::whereBelongsTo($user, 'author')->get();
|
||||||
|
```
|
||||||
|
|
||||||
|
## Keep application queries model-aware
|
||||||
|
|
||||||
|
Prefer Eloquent models and relationships for model-backed application queries. They preserve casts, scopes, and model table configuration. The query builder and raw SQL require table names. Use them when you intend their lower-level behavior.
|
||||||
|
|
||||||
|
Lower-level alternatives:
|
||||||
|
|
||||||
|
```php
|
||||||
|
DB::table('users')->where('active', true)->get();
|
||||||
|
|
||||||
|
$query->join('companies', 'companies.id', '=', 'users.company_id');
|
||||||
|
|
||||||
|
DB::select('SELECT * FROM orders WHERE status = ?', ['pending']);
|
||||||
|
```
|
||||||
|
|
||||||
|
Model-aware queries:
|
||||||
|
|
||||||
|
```php
|
||||||
|
User::where('active', true)->get();
|
||||||
|
Order::where('status', 'pending')->get();
|
||||||
|
```
|
||||||
|
|
||||||
|
When a query builder operation should follow a model's configured table name, use `(new User)->getTable()`. For complex joins or raw SQL, explicit table names may be clearer. When the schema can change, cover those table references with tests.
|
||||||
|
|
||||||
|
In migrations, use explicit table names rather than application models. Migrations are historical snapshots, but models and their scopes can change after you deploy a migration.
|
||||||
@@ -0,0 +1,77 @@
|
|||||||
|
# Error handling best practices
|
||||||
|
|
||||||
|
## Choose where to report and render exceptions
|
||||||
|
|
||||||
|
Laravel supports exception-specific methods and centralized handler callbacks. Follow the pattern the project already uses.
|
||||||
|
|
||||||
|
Exception methods keep behavior beside the exception definition:
|
||||||
|
|
||||||
|
```php
|
||||||
|
class InvalidOrderException extends Exception
|
||||||
|
{
|
||||||
|
public function report(): void
|
||||||
|
{
|
||||||
|
// Send the exception to a custom reporter.
|
||||||
|
}
|
||||||
|
|
||||||
|
public function render(Request $request): Response
|
||||||
|
{
|
||||||
|
return response()->view('errors.invalid-order', status: 422);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Centralized callbacks in `bootstrap/app.php` keep the application's exception policy together:
|
||||||
|
|
||||||
|
```php
|
||||||
|
->withExceptions(function (Exceptions $exceptions) {
|
||||||
|
$exceptions->report(function (InvalidOrderException $e) {
|
||||||
|
// Send the exception to a custom reporter.
|
||||||
|
});
|
||||||
|
$exceptions->render(function (InvalidOrderException $e, Request $request) {
|
||||||
|
return response()->view('errors.invalid-order', status: 422);
|
||||||
|
});
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
An exception's `report()` method suppresses Laravel's default reporting unless it returns `false`. A report callback allows default reporting unless it returns `false` or is chained with `stop()`. Use `ShouldntReport` or `dontReport()` when the handler should not report an exception at all. By contrast, returning `false` from a `render()` method or render callback defers to Laravel's default rendering.
|
||||||
|
|
||||||
|
## Mark exceptions the handler should not report
|
||||||
|
|
||||||
|
Implementing `ShouldntReport` prevents Laravel's exception handler from reporting that exception type and keeps the policy visible on the class. It does not prevent application code from logging the exception explicitly.
|
||||||
|
|
||||||
|
```php
|
||||||
|
class PodcastProcessingException extends Exception implements ShouldntReport {}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Throttle high-volume exception reports
|
||||||
|
|
||||||
|
A failing integration can flood logs or error tracking. Configure `throttle()` with a `Lottery` or `Limit` result to sample or rate-limit matching exception reports. Choose keys deliberately when separate exception classes, tenants, or integrations need independent limits.
|
||||||
|
|
||||||
|
## Prevent duplicate reports of one exception instance
|
||||||
|
|
||||||
|
Enable `dontReportDuplicates()` when the same exception object may pass through multiple `report($exception)` calls. It deduplicates by object identity, not by exception class or message.
|
||||||
|
|
||||||
|
## Define JSON rendering for API routes
|
||||||
|
|
||||||
|
By default, Laravel uses request content negotiation to decide whether to render an exception as JSON. If the application's API contract requires JSON regardless of the `Accept` header, define that policy explicitly for the relevant routes.
|
||||||
|
|
||||||
|
```php
|
||||||
|
$exceptions->shouldRenderJsonWhen(function (Request $request, Throwable $e) {
|
||||||
|
return $request->is('api/*') || $request->expectsJson();
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
## Add context to exception classes
|
||||||
|
|
||||||
|
Attach structured data to an exception through `context()`. Laravel merges that data into the exception's log context when the handler reports it.
|
||||||
|
|
||||||
|
```php
|
||||||
|
class InvalidOrderException extends Exception
|
||||||
|
{
|
||||||
|
public function context(): array
|
||||||
|
{
|
||||||
|
return ['order_id' => $this->orderId];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
# Events and notifications best practices
|
||||||
|
|
||||||
|
## Rely on event discovery
|
||||||
|
|
||||||
|
Laravel discovers listeners in the configured listener directories by inspecting type-hinted event arguments on `handle()` or `__invoke()` methods. Register listeners manually only when discovery is disabled, the listener is outside those directories, or explicit registration is clearer.
|
||||||
|
|
||||||
|
## Cache event discovery during production deployment
|
||||||
|
|
||||||
|
Cache discovered listeners during production deployment with `php artisan optimize` or `php artisan event:cache`. Rebuild the cache whenever listener definitions change.
|
||||||
|
|
||||||
|
## Use `ShouldDispatchAfterCommit` inside transactions
|
||||||
|
|
||||||
|
When you dispatch an event inside a database transaction, `ShouldDispatchAfterCommit` delays dispatch until all open database transactions commit. If a transaction rolls back, Laravel discards the event. The delay affects synchronous and queued listeners. It is not limited to queue timing.
|
||||||
|
|
||||||
|
```php
|
||||||
|
class OrderShipped implements ShouldDispatchAfterCommit {}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Queue slow notifications
|
||||||
|
|
||||||
|
Queue notifications that call external services, such as email, text messaging, or Slack, when they do not need to complete before the response. Keep a notification synchronous when immediate completion or failure feedback is part of the operation.
|
||||||
|
|
||||||
|
```php
|
||||||
|
class InvoicePaid extends Notification implements ShouldQueue
|
||||||
|
{
|
||||||
|
use Queueable;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Dispatch queued notifications after commit
|
||||||
|
|
||||||
|
A queued notification sent inside a database transaction can run before the transaction commits. Call `afterCommit()` on the queued notification, or enable the queue connection's `after_commit` option, when its delivery depends on committed data. Neither option has a scheduling effect on a synchronous notification.
|
||||||
|
|
||||||
|
```php
|
||||||
|
$user->notify((new InvoicePaid($invoice))->afterCommit());
|
||||||
|
```
|
||||||
|
|
||||||
|
## Route notification channels to dedicated queues
|
||||||
|
|
||||||
|
Different notification channels can have different latency and priority requirements. Implement `viaQueues()` when channels should use separate queues.
|
||||||
|
|
||||||
|
## Use on-demand notifications for non-user recipients
|
||||||
|
|
||||||
|
Avoid creating dummy models to send notifications to arbitrary addresses.
|
||||||
|
|
||||||
|
```php
|
||||||
|
Notification::route('mail', 'admin@example.com')->notify(new SystemAlert());
|
||||||
|
```
|
||||||
|
|
||||||
|
## Implement `HasLocalePreference` on notifiable models
|
||||||
|
|
||||||
|
Implement `HasLocalePreference::preferredLocale()` on a notifiable model when notifications and mailables should use the recipient's locale. Laravel also preserves that locale for queued delivery. An explicit `locale()` call can still override the preference for an individual notification.
|
||||||
@@ -0,0 +1,157 @@
|
|||||||
|
# HTTP client best practices
|
||||||
|
|
||||||
|
## Set explicit timeouts
|
||||||
|
|
||||||
|
Laravel's HTTP client has a 30-second response timeout by default. Choose response and connection timeouts that fit the service and the calling request or job. Retries can multiply the total elapsed time.
|
||||||
|
|
||||||
|
Less resilient:
|
||||||
|
|
||||||
|
```php
|
||||||
|
$response = Http::get('https://api.example.com/users');
|
||||||
|
```
|
||||||
|
|
||||||
|
Preferred:
|
||||||
|
|
||||||
|
```php
|
||||||
|
$response = Http::connectTimeout(3)
|
||||||
|
->timeout(5)
|
||||||
|
->get('https://api.example.com/users');
|
||||||
|
```
|
||||||
|
|
||||||
|
Define shared settings in a macro or a dedicated client:
|
||||||
|
|
||||||
|
```php
|
||||||
|
Http::macro('github', function () {
|
||||||
|
return Http::baseUrl('https://api.github.com')
|
||||||
|
->connectTimeout(3)
|
||||||
|
->timeout(10)
|
||||||
|
->withToken(config('services.github.token'));
|
||||||
|
});
|
||||||
|
|
||||||
|
$response = Http::github()->get('/repos/laravel/framework');
|
||||||
|
```
|
||||||
|
|
||||||
|
## Retry only safe operations
|
||||||
|
|
||||||
|
Retry transient connection failures, rate-limit responses, and server errors with an appropriate delay. Retry idempotent requests such as `GET` when the operation can safely run more than once. Retry a state-changing request only when the remote API supports an idempotency key or provides equivalent duplicate protection.
|
||||||
|
|
||||||
|
Unsafe without an idempotency guarantee:
|
||||||
|
|
||||||
|
```php
|
||||||
|
$response = Http::retry([100, 500, 1000])
|
||||||
|
->post('https://api.example.com/v1/charges', $data);
|
||||||
|
```
|
||||||
|
|
||||||
|
Safe for an idempotent request:
|
||||||
|
|
||||||
|
```php
|
||||||
|
$response = Http::connectTimeout(3)
|
||||||
|
->timeout(10)
|
||||||
|
->retry([100, 500, 1000], 0, function (Throwable $exception) {
|
||||||
|
return $exception instanceof ConnectionException
|
||||||
|
|| ($exception instanceof RequestException
|
||||||
|
&& ($exception->response->serverError() || $exception->response->status() === 429));
|
||||||
|
})
|
||||||
|
->get('https://api.example.com/data');
|
||||||
|
```
|
||||||
|
|
||||||
|
For a supported state-changing API, send a stable idempotency key for every attempt:
|
||||||
|
|
||||||
|
```php
|
||||||
|
$response = Http::withHeaders(['Idempotency-Key' => $paymentAttempt->uuid])
|
||||||
|
->connectTimeout(3)
|
||||||
|
->timeout(10)
|
||||||
|
->retry([100, 500, 1000], 0, function (Throwable $exception) {
|
||||||
|
return $exception instanceof ConnectionException
|
||||||
|
|| ($exception instanceof RequestException
|
||||||
|
&& ($exception->response->serverError() || $exception->response->status() === 429));
|
||||||
|
})
|
||||||
|
->post('https://api.example.com/v1/charges', $data);
|
||||||
|
```
|
||||||
|
|
||||||
|
## Handle errors explicitly
|
||||||
|
|
||||||
|
By default, the HTTP client returns responses for `4xx` and `5xx` status codes instead of throwing. Inspect the expected statuses or call `throw()` before consuming a success payload.
|
||||||
|
|
||||||
|
Unsafe when a success payload is expected:
|
||||||
|
|
||||||
|
```php
|
||||||
|
$user = Http::get('https://api.example.com/users/1')->json();
|
||||||
|
```
|
||||||
|
|
||||||
|
Preferred:
|
||||||
|
|
||||||
|
```php
|
||||||
|
$user = Http::connectTimeout(3)
|
||||||
|
->timeout(5)
|
||||||
|
->get('https://api.example.com/users/1')
|
||||||
|
->throw()
|
||||||
|
->json();
|
||||||
|
```
|
||||||
|
|
||||||
|
When graceful degradation is required, handle expected alternatives explicitly:
|
||||||
|
|
||||||
|
```php
|
||||||
|
$response = Http::connectTimeout(3)
|
||||||
|
->timeout(5)
|
||||||
|
->get('https://api.example.com/users/1');
|
||||||
|
|
||||||
|
if ($response->successful()) {
|
||||||
|
return $response->json();
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($response->notFound()) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
$response->throw();
|
||||||
|
```
|
||||||
|
|
||||||
|
## Pool independent requests
|
||||||
|
|
||||||
|
Use `Http::pool()` when several independent requests can run concurrently. Pooling changes execution time, not error handling. Inspect or throw for each response as needed.
|
||||||
|
|
||||||
|
```php
|
||||||
|
use Illuminate\Http\Client\Pool;
|
||||||
|
|
||||||
|
$responses = Http::pool(fn (Pool $pool) => [
|
||||||
|
$pool->as('users')->connectTimeout(3)->timeout(5)
|
||||||
|
->get('https://api.example.com/users'),
|
||||||
|
$pool->as('posts')->connectTimeout(3)->timeout(5)
|
||||||
|
->get('https://api.example.com/posts'),
|
||||||
|
]);
|
||||||
|
|
||||||
|
$users = $responses['users']->throw()->json();
|
||||||
|
$posts = $responses['posts']->throw()->json();
|
||||||
|
```
|
||||||
|
|
||||||
|
## Fake HTTP requests in tests
|
||||||
|
|
||||||
|
Use `Http::fake()` for external integrations, and use `Http::preventStrayRequests()` when an unexpected real request should fail the test. Also test timeouts, connection failures, and error responses that the application handles.
|
||||||
|
|
||||||
|
```php
|
||||||
|
it('syncs a user from the API', function () {
|
||||||
|
Http::preventStrayRequests();
|
||||||
|
|
||||||
|
Http::fake([
|
||||||
|
'api.example.com/users/1' => Http::response([
|
||||||
|
'name' => 'John Doe',
|
||||||
|
'email' => 'john@example.com',
|
||||||
|
]),
|
||||||
|
]);
|
||||||
|
|
||||||
|
(new UserSyncService)->sync(1);
|
||||||
|
|
||||||
|
Http::assertSent(fn (Request $request) =>
|
||||||
|
$request->url() === 'https://api.example.com/users/1'
|
||||||
|
);
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
For example, to test the integration's failure path, fake a connection failure:
|
||||||
|
|
||||||
|
```php
|
||||||
|
Http::fake([
|
||||||
|
'api.example.com/*' => Http::failedConnection(),
|
||||||
|
]);
|
||||||
|
```
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
# Mail best practices
|
||||||
|
|
||||||
|
## Queue slow mail delivery
|
||||||
|
|
||||||
|
Implement `ShouldQueue` on a mailable when delivery should normally happen in the background. Laravel queues that mailable even when the call site uses `Mail::send()`.
|
||||||
|
|
||||||
|
```php
|
||||||
|
class OrderShipped extends Mailable implements ShouldQueue
|
||||||
|
{
|
||||||
|
use Queueable, SerializesModels;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Keep mail synchronous when the caller must know immediately whether delivery was accepted, or when no queue worker is available.
|
||||||
|
|
||||||
|
## Dispatch queued mail after commit
|
||||||
|
|
||||||
|
A queue worker can process a queued mailable dispatched during a database transaction before the transaction commits. Call `afterCommit()` on the mailable, or enable the queue connection's `after_commit` option, when the mail depends on committed records.
|
||||||
|
|
||||||
|
```php
|
||||||
|
Mail::to($user)->send(
|
||||||
|
(new OrderShipped($order))->afterCommit()
|
||||||
|
);
|
||||||
|
```
|
||||||
|
|
||||||
|
If the transaction rolls back, Laravel does not dispatch an after-commit mailable. The after-commit setting affects only queued mail. It does not defer synchronous delivery.
|
||||||
|
|
||||||
|
## Assert the delivery mode
|
||||||
|
|
||||||
|
Use `Mail::assertQueued()` for queued mailables and `Mail::assertSent()` for synchronously sent mailables.
|
||||||
|
|
||||||
|
Incorrect for a mailable that implements `ShouldQueue`:
|
||||||
|
|
||||||
|
```php
|
||||||
|
Mail::assertSent(OrderShipped::class);
|
||||||
|
```
|
||||||
|
|
||||||
|
Correct:
|
||||||
|
|
||||||
|
```php
|
||||||
|
Mail::assertQueued(OrderShipped::class);
|
||||||
|
```
|
||||||
|
|
||||||
|
## Use Markdown mailables when they fit
|
||||||
|
|
||||||
|
Markdown mailables render HTML and plain-text versions from Laravel's mail components and support publishable themes. They suit conventional transactional messages. A custom HTML and text pair may fit a specialized design better.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
php artisan make:mail OrderShipped --markdown=mail.orders.shipped
|
||||||
|
```
|
||||||
|
|
||||||
|
## Separate content and delivery tests
|
||||||
|
|
||||||
|
Test rendered content by instantiating the mailable and using assertions such as `assertSeeInHtml()` and `assertSeeInText()`. Test delivery separately with `Mail::fake()` and `assertSent()` or `assertQueued()` so failures identify the affected behavior.
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
# Migration best practices
|
||||||
|
|
||||||
|
## Generate migrations with Artisan
|
||||||
|
|
||||||
|
Use `php artisan make:migration` to generate the timestamped filename and migration structure.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
php artisan make:migration create_posts_table
|
||||||
|
php artisan make:migration add_slug_to_posts_table
|
||||||
|
```
|
||||||
|
|
||||||
|
## Define foreign-key constraints deliberately
|
||||||
|
|
||||||
|
Use `constrained()` when its naming conventions and default actions match the relationship. Specify the table or delete behavior when they do not.
|
||||||
|
|
||||||
|
```php
|
||||||
|
$table->foreignId('user_id')->constrained()->cascadeOnDelete();
|
||||||
|
$table->foreignId('author_id')->constrained('users');
|
||||||
|
```
|
||||||
|
|
||||||
|
Do not add a duplicate single-column index without checking the database driver's treatment of foreign-key indexes and the indexes already created by the migration.
|
||||||
|
|
||||||
|
## Treat deployed migrations as immutable
|
||||||
|
|
||||||
|
After a migration has run in a shared or production environment, create a new migration for later changes. Editing the old file makes fresh installations differ from upgraded installations.
|
||||||
|
|
||||||
|
For a local migration that has not been shared or deployed, editing and rerunning it may be simpler.
|
||||||
|
|
||||||
|
## Design indexes for real queries
|
||||||
|
|
||||||
|
Add indexes based on query patterns, selectivity, write cost, and the database's ability to use composite indexes. A column that appears in `WHERE`, `ORDER BY`, or `JOIN` does not automatically need its own index.
|
||||||
|
|
||||||
|
Declare each selected index in the schema migration that creates or changes the relevant table. Confirm important indexes with representative data and the database's query plan. Avoid redundant indexes whose leading columns duplicate an existing index without serving a distinct query. See the database performance and advanced query rules for index selection and column-order guidance.
|
||||||
|
|
||||||
|
## Stage changes that affect existing rows
|
||||||
|
|
||||||
|
Adding a required or unique column to a populated table often needs multiple deployment-safe steps. Add a nullable column, deploy code that can handle both states, backfill existing rows in bounded chunks, then add the required constraint or index after the data is valid.
|
||||||
|
|
||||||
|
Do not assume this migration is safe on a populated table:
|
||||||
|
|
||||||
|
```php
|
||||||
|
$table->string('slug')->unique();
|
||||||
|
```
|
||||||
|
|
||||||
|
Large backfills usually work better as an observable, restartable command or job than inside a schema migration. Small deterministic data changes may be reasonable in a migration when you understand their locking, transaction, and deployment behavior.
|
||||||
|
|
||||||
|
## Mirror defaults only when unsaved models need them
|
||||||
|
|
||||||
|
The database applies a default when it inserts a row, not when you instantiate a model. Mirror the value in the model's `$attributes` only when application code must observe that default before persistence, and keep both definitions in sync.
|
||||||
|
|
||||||
|
```php
|
||||||
|
// Migration
|
||||||
|
$table->string('status')->default('pending');
|
||||||
|
|
||||||
|
// Model
|
||||||
|
protected $attributes = [
|
||||||
|
'status' => 'pending',
|
||||||
|
];
|
||||||
|
```
|
||||||
|
|
||||||
|
## Make rollbacks honest
|
||||||
|
|
||||||
|
Implement `down()` when you can safely reverse the change. A rollback that drops populated columns or cannot restore transformed data is destructive even if it is syntactically reversible. Document that limitation and prefer a forward-fix migration in production.
|
||||||
|
|
||||||
|
## Keep migrations focused
|
||||||
|
|
||||||
|
Keep each migration small enough to reason about, deploy, and reverse. Separate long-running backfills from schema changes when the split reduces locks and supports phased deployment. Do not split related operations only to enforce a blanket separation between data definition and data manipulation.
|
||||||
@@ -0,0 +1,117 @@
|
|||||||
|
# Queue and job best practices
|
||||||
|
|
||||||
|
## Keep reservation time longer than execution time
|
||||||
|
|
||||||
|
For queue drivers that use Laravel's `retry_after` setting, configure it to exceed the longest worker or job timeout by a safety margin. When a reservation expires, another worker can reserve the same job while the first process is still running. Keep the worker's `--timeout` several seconds shorter than `retry_after`.
|
||||||
|
|
||||||
|
```php
|
||||||
|
// Job
|
||||||
|
public $timeout = 120;
|
||||||
|
|
||||||
|
// config/queue.php for the connection
|
||||||
|
'retry_after' => 150,
|
||||||
|
```
|
||||||
|
|
||||||
|
Amazon Simple Queue Service uses its visibility timeout instead of Laravel's `retry_after`. Configure that timeout at the queue level. Because workers can also stop after side effects but before acknowledging a job, make important jobs idempotent even with correct timeout settings.
|
||||||
|
|
||||||
|
## Back off transient failures
|
||||||
|
|
||||||
|
Use progressively longer delays when a dependency needs time to recover. Do not retry permanent validation or business-rule failures.
|
||||||
|
|
||||||
|
```php
|
||||||
|
class SyncWithStripe implements ShouldQueue
|
||||||
|
{
|
||||||
|
public $tries = 4;
|
||||||
|
|
||||||
|
public $backoff = [1, 5, 10];
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Rate-limiting and exception-throttling middleware can release jobs back to the queue. Released attempts may still count toward the maximum attempt limit, so configure `$tries` or `retryUntil()` to allow the intended retry window.
|
||||||
|
|
||||||
|
## Use unique jobs for dispatch deduplication
|
||||||
|
|
||||||
|
Implement `ShouldBeUnique` when only one queued instance of a logical job should exist. Uniqueness uses a cache lock. It does not replace idempotent processing or a database constraint.
|
||||||
|
|
||||||
|
```php
|
||||||
|
class GenerateInvoice implements ShouldQueue, ShouldBeUnique
|
||||||
|
{
|
||||||
|
public $uniqueFor = 3600;
|
||||||
|
|
||||||
|
public function uniqueId(): string
|
||||||
|
{
|
||||||
|
return (string) $this->order->id;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
All dispatching processes must use a shared cache that supports locks. Unique-job constraints do not apply to jobs within batches.
|
||||||
|
|
||||||
|
Use `ShouldBeUniqueUntilProcessing` only when the lock should release immediately before processing begins. Another instance can then be dispatched while the first is running:
|
||||||
|
|
||||||
|
```php
|
||||||
|
class UpdateSearchIndex implements ShouldQueue, ShouldBeUniqueUntilProcessing
|
||||||
|
{
|
||||||
|
// ...
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Handle terminal failure when needed
|
||||||
|
|
||||||
|
Implement `failed()` when the application must update state, alert an operator, or record domain-specific context after all attempts are exhausted. Logging every failure in each job may duplicate the queue system's failure reporting.
|
||||||
|
|
||||||
|
Laravel invokes `failed()` on a new job instance, so changes made to the job during `handle()` are not available in `failed()`.
|
||||||
|
|
||||||
|
```php
|
||||||
|
public function failed(?Throwable $exception): void
|
||||||
|
{
|
||||||
|
$this->podcast->update(['status' => 'failed']);
|
||||||
|
|
||||||
|
Log::error('Podcast processing failed', [
|
||||||
|
'podcast_id' => $this->podcast->id,
|
||||||
|
'exception' => $exception,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Rate limit external calls
|
||||||
|
|
||||||
|
Use queue middleware such as `RateLimited` when jobs share a third-party API quota. Define the named limiter and choose release delays and attempt limits together.
|
||||||
|
|
||||||
|
```php
|
||||||
|
public function middleware(): array
|
||||||
|
{
|
||||||
|
return [new RateLimited('external-api')];
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Batch jobs for group coordination
|
||||||
|
|
||||||
|
Use `Bus::batch()` to monitor a group of jobs and run callbacks when the batch completes or encounters failures. A batch is not a database transaction. Laravel does not roll back completed jobs when another job fails. By default, one failed job cancels the batch. Call `allowFailures()` only when partial failure is acceptable.
|
||||||
|
|
||||||
|
```php
|
||||||
|
Bus::batch([
|
||||||
|
new ImportCsvChunk($chunk1),
|
||||||
|
new ImportCsvChunk($chunk2),
|
||||||
|
])
|
||||||
|
->then(fn (Batch $batch) => Notification::send($user, new ImportComplete))
|
||||||
|
->catch(fn (Batch $batch, Throwable $exception) => Log::error('Import batch failed', [
|
||||||
|
'exception' => $exception,
|
||||||
|
]))
|
||||||
|
->dispatch();
|
||||||
|
```
|
||||||
|
|
||||||
|
## Configure time-based retry limits deliberately
|
||||||
|
|
||||||
|
Use `retryUntil()` as the time-based alternative to a maximum attempt count. Laravel may attempt the job any number of times until this deadline, subject to other failure conditions such as maximum exceptions. `retryUntil()` takes precedence over attempt-based limits, so you do not need to set `$tries = 0`.
|
||||||
|
|
||||||
|
```php
|
||||||
|
public function retryUntil(): DateTimeInterface
|
||||||
|
{
|
||||||
|
return now()->addHours(4);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Use Horizon for Redis queue operations
|
||||||
|
|
||||||
|
Laravel Horizon provides monitoring, balancing, metrics, and supervisor configuration for Redis queues. It does not support non-Redis queue drivers.
|
||||||
@@ -0,0 +1,106 @@
|
|||||||
|
# Routing and controller best practices
|
||||||
|
|
||||||
|
## Use implicit route model binding
|
||||||
|
|
||||||
|
Let Laravel resolve models from route parameters when the default lookup and missing-model behavior fit the endpoint.
|
||||||
|
|
||||||
|
Instead of manual lookup:
|
||||||
|
|
||||||
|
```php
|
||||||
|
public function show(int $id): View
|
||||||
|
{
|
||||||
|
$post = Post::findOrFail($id);
|
||||||
|
|
||||||
|
return view('posts.show', ['post' => $post]);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Use route model binding:
|
||||||
|
|
||||||
|
```php
|
||||||
|
public function show(Post $post): View
|
||||||
|
{
|
||||||
|
return view('posts.show', ['post' => $post]);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Scope nested bindings
|
||||||
|
|
||||||
|
Use scoped bindings when a nested resource must belong to its parent. Scoped bindings constrain model resolution. They do not replace authorization.
|
||||||
|
|
||||||
|
```php
|
||||||
|
Route::get('/users/{user}/posts/{post}', function (User $user, Post $post) {
|
||||||
|
// The resolved post belongs to the resolved user.
|
||||||
|
})->scopeBindings();
|
||||||
|
```
|
||||||
|
|
||||||
|
## Use resource routes for resourceful actions
|
||||||
|
|
||||||
|
Use `Route::resource()` or `Route::apiResource()` when the endpoint follows Laravel's resource-controller actions. Define explicit routes when the behavior does not fit that vocabulary.
|
||||||
|
|
||||||
|
```php
|
||||||
|
Route::resource('posts', PostController::class);
|
||||||
|
|
||||||
|
// Alternatively, for an API-only resource:
|
||||||
|
Route::apiResource('posts', ApiPostController::class);
|
||||||
|
```
|
||||||
|
|
||||||
|
`apiResource()` omits the HTML-oriented `create` and `edit` routes. It does not add an `/api` prefix. That prefix comes from the application's API route configuration.
|
||||||
|
|
||||||
|
## Organize controllers around resources
|
||||||
|
|
||||||
|
By default, organize each controller around one resource and use Laravel's standard resource actions: `index`, `show`, `create`, `store`, `edit`, `update`, and `destroy`. This convention keeps routes predictable and prevents controllers from accumulating unrelated behavior.
|
||||||
|
|
||||||
|
When a controller needs a custom action such as `publish`, `approve`, or `archive`, first consider whether that behavior represents a separate resource. A focused resource controller gives the behavior its own authorization, validation, and middleware boundary.
|
||||||
|
|
||||||
|
Custom action on the primary controller:
|
||||||
|
|
||||||
|
```php
|
||||||
|
Route::post('/podcasts/{podcast}/publish', [PodcastController::class, 'publish']);
|
||||||
|
```
|
||||||
|
|
||||||
|
The published podcast modeled as a resource:
|
||||||
|
|
||||||
|
```php
|
||||||
|
Route::post('/published-podcasts/{podcast}', [PublishedPodcastController::class, 'store'])
|
||||||
|
->name('published-podcasts.store');
|
||||||
|
|
||||||
|
Route::delete('/published-podcasts/{podcast}', [PublishedPodcastController::class, 'destroy'])
|
||||||
|
->name('published-podcasts.destroy');
|
||||||
|
```
|
||||||
|
|
||||||
|
```php
|
||||||
|
class PublishedPodcastController extends Controller
|
||||||
|
{
|
||||||
|
public function store(Podcast $podcast): RedirectResponse
|
||||||
|
{
|
||||||
|
$podcast->publish();
|
||||||
|
|
||||||
|
return back();
|
||||||
|
}
|
||||||
|
|
||||||
|
public function destroy(Podcast $podcast): RedirectResponse
|
||||||
|
{
|
||||||
|
$podcast->unpublish();
|
||||||
|
|
||||||
|
return back();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Treat a custom verb as a design signal, not proof that another controller is required. Use query parameters for simple filtering, and keep an explicit action route when modeling the operation as a resource would obscure the domain or conflict with established project conventions.
|
||||||
|
|
||||||
|
## Keep controllers focused on HTTP concerns
|
||||||
|
|
||||||
|
Controllers should coordinate HTTP input, authorization, validation, an application operation, and the response. Extract substantial or reusable business logic, but do not introduce an action or service only to satisfy an arbitrary line limit.
|
||||||
|
|
||||||
|
```php
|
||||||
|
public function store(StorePostRequest $request, CreatePostAction $create): RedirectResponse
|
||||||
|
{
|
||||||
|
$post = $create->handle($request->validated());
|
||||||
|
|
||||||
|
return redirect()->route('posts.show', $post);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
A form request can perform validation and authorization before the controller runs. Do not repeat its rules in the controller. Keep simple, endpoint-specific validation inline when extraction would not improve reuse or clarity. See the validation rules for details.
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
# Task scheduling best practices
|
||||||
|
|
||||||
|
## Prevent unwanted overlap
|
||||||
|
|
||||||
|
Use `withoutOverlapping()` when a second run must not begin while the previous run holds the lock. Use it for variable-duration tasks that are not safe to run concurrently.
|
||||||
|
|
||||||
|
```php
|
||||||
|
Schedule::command('reports:generate')
|
||||||
|
->everyFifteenMinutes()
|
||||||
|
->withoutOverlapping(30);
|
||||||
|
```
|
||||||
|
|
||||||
|
The optional value is the lock expiration time in minutes, not the task timeout. Choose the value carefully. The default is 24 hours, and an expiration that is too short can permit overlap while the first task still runs. Clear stale locks with `php artisan schedule:clear-cache`. The task itself should still tolerate retries and partial execution where practical.
|
||||||
|
|
||||||
|
## Run a task on one server
|
||||||
|
|
||||||
|
Use `onOneServer()` when only one scheduler node should run an eligible task. Scheduler nodes must use the same default cache store, and that store must support atomic locks. Supported stores include `database`, `memcached`, `dynamodb`, and `redis`.
|
||||||
|
|
||||||
|
```php
|
||||||
|
Schedule::command('billing:charge')->daily()->onOneServer();
|
||||||
|
```
|
||||||
|
|
||||||
|
Name scheduled closures before applying `onOneServer()`, especially when scheduling the same closure with different parameters, so each task has a distinct lock identity.
|
||||||
|
|
||||||
|
## Run eligible commands in the background
|
||||||
|
|
||||||
|
Tasks due at the same time run sequentially by default. Use `runInBackground()` when an independent, long-running scheduled command should not delay later tasks.
|
||||||
|
|
||||||
|
```php
|
||||||
|
Schedule::command('analytics:process')->hourly()->runInBackground();
|
||||||
|
```
|
||||||
|
|
||||||
|
Laravel restricts `runInBackground()` to tasks scheduled with `command()` and `exec()`. It is not available for scheduled closures. Give background processes logging and failure monitoring.
|
||||||
|
|
||||||
|
## Restrict tasks by environment
|
||||||
|
|
||||||
|
Use `environments()` when a task should run only in named application environments. Treat `environments()` as an operational safeguard, not an authorization control.
|
||||||
|
|
||||||
|
```php
|
||||||
|
Schedule::command('billing:charge')
|
||||||
|
->monthly()
|
||||||
|
->environments(['production']);
|
||||||
|
```
|
||||||
|
|
||||||
|
## Group shared configuration
|
||||||
|
|
||||||
|
Use schedule groups when several tasks share frequency or constraints.
|
||||||
|
|
||||||
|
```php
|
||||||
|
Schedule::daily()
|
||||||
|
->onOneServer()
|
||||||
|
->timezone('America/New_York')
|
||||||
|
->group(function () {
|
||||||
|
Schedule::command('emails:send --force');
|
||||||
|
Schedule::command('emails:prune');
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
## Bound work inside the task
|
||||||
|
|
||||||
|
The scheduler does not provide a `takeUntilTimeout()` event method or terminate arbitrary tasks at a deadline. Bound work in the command or job itself by processing finite chunks, checking a deadline, or dispatching queue jobs with suitable timeouts. Use operating-system or process controls when hard termination is required.
|
||||||
@@ -0,0 +1,156 @@
|
|||||||
|
# Security best practices
|
||||||
|
|
||||||
|
## Control mass assignment
|
||||||
|
|
||||||
|
Define `$fillable` when a model is populated from request-derived arrays, or deliberately guard attributes by another consistent model convention. Laravel models guard all attributes by default. `$guarded = []` opts out of that protection.
|
||||||
|
|
||||||
|
```php
|
||||||
|
class User extends Model
|
||||||
|
{
|
||||||
|
protected $fillable = [
|
||||||
|
'name',
|
||||||
|
'email',
|
||||||
|
'password',
|
||||||
|
];
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Do not pass untrusted request data to a model with `$guarded = []`. Mass-assignment protection controls which attributes `create()`, `fill()`, and `update()` may set. It does not validate values or authorize the operation.
|
||||||
|
|
||||||
|
## Authorize protected actions
|
||||||
|
|
||||||
|
Use policies, gates, or form request authorization for actions that depend on the current user's permissions. Authentication alone does not establish permission, and validation is not authorization.
|
||||||
|
|
||||||
|
```php
|
||||||
|
public function update(UpdatePostRequest $request, Post $post): RedirectResponse
|
||||||
|
{
|
||||||
|
Gate::authorize('update', $post);
|
||||||
|
|
||||||
|
$post->update($request->validated());
|
||||||
|
|
||||||
|
return redirect()->route('posts.show', $post);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Authorization may instead live in the form request:
|
||||||
|
|
||||||
|
```php
|
||||||
|
public function authorize(): bool
|
||||||
|
{
|
||||||
|
return $this->user()?->can('update', $this->route('post')) ?? false;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Public actions intentionally available to everyone do not need a redundant authorization check.
|
||||||
|
|
||||||
|
## Bind query parameters
|
||||||
|
|
||||||
|
Use Eloquent, the query builder, or explicit bindings instead of interpolating untrusted values into Structured Query Language (SQL). Bindings protect values, not identifiers such as column names or sort directions. Map user-selected identifiers to an allow-list.
|
||||||
|
|
||||||
|
Incorrect:
|
||||||
|
|
||||||
|
```php
|
||||||
|
DB::select("SELECT * FROM users WHERE name = '{$request->name}'");
|
||||||
|
```
|
||||||
|
|
||||||
|
Correct:
|
||||||
|
|
||||||
|
```php
|
||||||
|
User::where('name', $request->name)->get();
|
||||||
|
User::whereRaw('LOWER(name) = ?', [$request->string('name')->lower()->toString()])->get();
|
||||||
|
```
|
||||||
|
|
||||||
|
## Escape output in its context
|
||||||
|
|
||||||
|
Blade's `{{ }}` syntax HTML-escapes output. Use `{!! !!}` only for content sanitized for the exact HTML context where it renders. Escaping rules differ for HTML, URLs, JavaScript, and Cascading Style Sheets.
|
||||||
|
|
||||||
|
Incorrect for untrusted content:
|
||||||
|
|
||||||
|
```blade
|
||||||
|
{!! $user->bio !!}
|
||||||
|
```
|
||||||
|
|
||||||
|
Correct:
|
||||||
|
|
||||||
|
```blade
|
||||||
|
{{ $user->bio }}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Apply cross-site request forgery protection
|
||||||
|
|
||||||
|
Include `@csrf` in state-changing Blade forms handled by Laravel's `web` middleware. Routes intentionally excluded from cross-site request forgery (CSRF) verification, such as validated third-party webhooks, need their own authenticity check.
|
||||||
|
|
||||||
|
```blade
|
||||||
|
<form method="POST" action="/posts">
|
||||||
|
@csrf
|
||||||
|
<input type="text" name="title">
|
||||||
|
</form>
|
||||||
|
```
|
||||||
|
|
||||||
|
Inertia applications commonly use Axios, which returns the encrypted `XSRF-TOKEN` cookie in the `X-XSRF-TOKEN` header. When you use another HTTP client, confirm equivalent configuration. Do not disable CSRF protection only to fix a token mismatch.
|
||||||
|
|
||||||
|
## Rate limit sensitive endpoints
|
||||||
|
|
||||||
|
Apply suitable rate limits to login attempts, password recovery, verification messages, and expensive or abuse-prone application programming interface (API) routes. Choose the limiter key deliberately. An Internet Protocol (IP) address alone can unfairly group users behind a shared network. An account identifier alone can enable targeted denial of service.
|
||||||
|
|
||||||
|
```php
|
||||||
|
RateLimiter::for('login', function (Request $request) {
|
||||||
|
return Limit::perMinute(5)->by(Str::transliterate(
|
||||||
|
Str::lower($request->string('email')).'|'.$request->ip()
|
||||||
|
));
|
||||||
|
});
|
||||||
|
|
||||||
|
Route::post('/login', LoginController::class)->middleware('throttle:login');
|
||||||
|
```
|
||||||
|
|
||||||
|
Rate limiting reduces abuse. It does not replace authentication, authorization, or upstream denial-of-service protection.
|
||||||
|
|
||||||
|
## Validate and store uploads safely
|
||||||
|
|
||||||
|
Validate the expected content type, the size, and the dimensions where relevant. Laravel's `mimes` rule reads the file contents and guesses a Multipurpose Internet Mail Extensions (MIME) type corresponding to the listed extensions. It does not validate the user-assigned filename extension. The `extensions` rule checks that extension. Do not use it by itself.
|
||||||
|
|
||||||
|
```php
|
||||||
|
public function rules(): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
'avatar' => ['required', 'image', 'mimes:jpg,jpeg,png,webp', 'max:2048'],
|
||||||
|
];
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Use Laravel's storage methods to generate a filename, and store untrusted files outside a publicly executable location. Public files can require additional controls, such as image re-encoding, content-disposition headers, and explicit blocking of active formats.
|
||||||
|
|
||||||
|
```php
|
||||||
|
$path = $request->file('avatar')->store('avatars');
|
||||||
|
```
|
||||||
|
|
||||||
|
## Keep secrets out of application code
|
||||||
|
|
||||||
|
Do not commit populated environment files or hard-code credentials. Read environment variables in configuration files, then use `config()` in application code so configuration caching works. See the configuration rules for encrypted environment files and external secret stores.
|
||||||
|
|
||||||
|
## Audit dependencies
|
||||||
|
|
||||||
|
Run `composer audit` regularly and in continuous integration. Review findings for exploitability and update or mitigate affected packages promptly.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
composer audit
|
||||||
|
```
|
||||||
|
|
||||||
|
## Encrypt sensitive attributes when appropriate
|
||||||
|
|
||||||
|
Use an `encrypted` cast for sensitive values that must be recoverable, and use `$hidden` to omit them from array and JavaScript Object Notation (JSON) serialization. Hidden attributes remain accessible in PHP, and encryption does not replace access control. You cannot meaningfully query encrypted values. Store them in a `TEXT` or larger column because ciphertext length varies.
|
||||||
|
|
||||||
|
```php
|
||||||
|
class Integration extends Model
|
||||||
|
{
|
||||||
|
protected $hidden = ['api_key', 'api_secret'];
|
||||||
|
|
||||||
|
protected function casts(): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
'api_key' => 'encrypted',
|
||||||
|
'api_secret' => 'encrypted',
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
@@ -0,0 +1,110 @@
|
|||||||
|
# Convention and style best practices
|
||||||
|
|
||||||
|
## Follow project naming conventions
|
||||||
|
|
||||||
|
Prefer Laravel's conventions in new code, but preserve an established project convention unless a coordinated rename is worthwhile.
|
||||||
|
|
||||||
|
| Element | Convention | Example |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| Controller | Singular resource name | `ArticleController` |
|
||||||
|
| Model | Singular StudlyCase | `User` |
|
||||||
|
| Table | Plural snake_case | `article_comments` |
|
||||||
|
| Pivot table | Singular model names in alphabetical order, in snake_case | `article_user` |
|
||||||
|
| Column | snake_case | `meta_title` |
|
||||||
|
| Conventional foreign key | Singular model name plus `_id`, in snake_case | `article_id` |
|
||||||
|
| Resource URI | Plural resource | `articles/1` |
|
||||||
|
| Route name | Dotted segments, with snake_case within a segment when needed | `users.show_active` |
|
||||||
|
| Method | camelCase | `getAll` |
|
||||||
|
| Variable | camelCase | `$articlesWithAuthor` |
|
||||||
|
| Collection | Descriptive and plural | `$activeUsers` |
|
||||||
|
| Object | Descriptive and singular | `$activeUser` |
|
||||||
|
| View | kebab-case | `show-filtered.blade.php` |
|
||||||
|
| Configuration file | snake_case | `google_calendar.php` |
|
||||||
|
| Enumeration | Singular StudlyCase | `UserType` |
|
||||||
|
|
||||||
|
## Prefer clear, idiomatic syntax
|
||||||
|
|
||||||
|
Use Laravel helpers and query methods when they communicate intent more directly. Do not shorten code when the result is ambiguous or loses useful type information.
|
||||||
|
|
||||||
|
| More verbose | Idiomatic alternative |
|
||||||
|
| --- | --- |
|
||||||
|
| `Session::get('cart')` | `session('cart')` |
|
||||||
|
| `$request->session()->get('cart')` | `session('cart')` |
|
||||||
|
| `return Redirect::back()` | `return back()` |
|
||||||
|
| `Carbon::now()` | `now()` |
|
||||||
|
| `->where('column', '=', 1)` | `->where('column', 1)` |
|
||||||
|
| `->orderBy('created_at', 'desc')` | `->latest()` |
|
||||||
|
| `->orderBy('created_at', 'asc')` | `->oldest()` |
|
||||||
|
| `->first()?->name` | `->value('name')` when only that value is needed |
|
||||||
|
|
||||||
|
Use typed request accessors such as `$request->string()`, `$request->integer()`, and `$request->boolean()` when their coercion matches the operation.
|
||||||
|
|
||||||
|
## Use utilities when they clarify intent
|
||||||
|
|
||||||
|
Laravel's `Str`, `Arr`, `Number`, and `Uri` utilities provide expressive operations and framework-consistent behavior. Prefer them when they are clearer or safer than an equivalent PHP operation, not as a replacement for every built-in function.
|
||||||
|
|
||||||
|
```php
|
||||||
|
$slug = Str::slug($title);
|
||||||
|
$short = Str::limit($text, 100);
|
||||||
|
$class = class_basename(User::class);
|
||||||
|
$result = Str::of($input)->trim()->replace('_', '-')->lower();
|
||||||
|
```
|
||||||
|
|
||||||
|
Use `Arr` for dot notation and common transformations:
|
||||||
|
|
||||||
|
```php
|
||||||
|
$name = Arr::get($array, 'user.name', 'default');
|
||||||
|
$public = Arr::only($attributes, ['name', 'email']);
|
||||||
|
```
|
||||||
|
|
||||||
|
Use `Number` for localized display formatting, not for values you store or calculate:
|
||||||
|
|
||||||
|
```php
|
||||||
|
Number::format(1000000);
|
||||||
|
Number::currency(1500, 'USD');
|
||||||
|
Number::fileSize(1024 * 1024);
|
||||||
|
```
|
||||||
|
|
||||||
|
Use `Uri` when a structured API helps you build or transform a uniform resource identifier (URI):
|
||||||
|
|
||||||
|
```php
|
||||||
|
$uri = Uri::of('https://example.com/search')
|
||||||
|
->withQuery(['q' => 'laravel', 'page' => 1]);
|
||||||
|
```
|
||||||
|
|
||||||
|
Before using newer utility classes or methods, check the documentation for the project's Laravel version.
|
||||||
|
|
||||||
|
## Keep presentation code maintainable
|
||||||
|
|
||||||
|
Prefer the project's asset pipeline, components, and existing conventions for substantial JavaScript and Cascading Style Sheets (CSS). Small page-specific scripts or styles can be reasonable in Blade layouts or stacks. Avoid mixing large behavior and style blocks into templates.
|
||||||
|
|
||||||
|
Pass server data with an encoding that fits its context. For example, Blade's `Js::from()` safely formats data for JavaScript:
|
||||||
|
|
||||||
|
```blade
|
||||||
|
<script>
|
||||||
|
const article = {{ Js::from($article) }};
|
||||||
|
</script>
|
||||||
|
```
|
||||||
|
|
||||||
|
Data attributes are useful for small scalar values, but serializing a large model into an attribute can expose unnecessary fields and complicate escaping.
|
||||||
|
|
||||||
|
## Write comments that explain why
|
||||||
|
|
||||||
|
Prefer clear names and small units of code over comments that restate an operation. Add concise comments for non-obvious constraints, tradeoffs, workarounds, regular expressions, or external behavior that the code cannot express by itself. Keep comments accurate when behavior changes.
|
||||||
|
|
||||||
|
Unhelpful:
|
||||||
|
|
||||||
|
```php
|
||||||
|
// Check whether the query has joins.
|
||||||
|
if (count((array) $builder->getQuery()->joins) > 0) {
|
||||||
|
// ...
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Clearer:
|
||||||
|
|
||||||
|
```php
|
||||||
|
if ($this->hasJoins()) {
|
||||||
|
// ...
|
||||||
|
}
|
||||||
|
```
|
||||||
@@ -0,0 +1,89 @@
|
|||||||
|
# Validation and forms best practices
|
||||||
|
|
||||||
|
## Extract validation when it improves the boundary
|
||||||
|
|
||||||
|
Use a form request when validation or authorization is substantial, reused, or clearer outside the controller. Inline `$request->validate()` remains appropriate for a small, endpoint-specific rule set.
|
||||||
|
|
||||||
|
```php
|
||||||
|
public function store(StorePostRequest $request): RedirectResponse
|
||||||
|
{
|
||||||
|
$post = Post::create($request->validated());
|
||||||
|
|
||||||
|
return redirect()->route('posts.show', $post);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
A form request's `authorize()` method can enforce access to the operation. Validation checks the shape and values of the input. Validation alone does not authorize the user.
|
||||||
|
|
||||||
|
## Prefer readable rule syntax
|
||||||
|
|
||||||
|
Array syntax combines with rule objects and avoids delimiter problems. Prefer array syntax in new code when it improves readability, and keep the local style consistent.
|
||||||
|
|
||||||
|
```php
|
||||||
|
'email' => ['required', 'email', Rule::unique('users')],
|
||||||
|
```
|
||||||
|
|
||||||
|
String syntax remains valid for simple rules:
|
||||||
|
|
||||||
|
```php
|
||||||
|
'email' => 'required|email|unique:users',
|
||||||
|
```
|
||||||
|
|
||||||
|
## Use only the validated data you intend
|
||||||
|
|
||||||
|
Use `validated()` or `safe()` instead of `$request->all()` when passing request data onward. When the validation rules also cover control fields or nested data, select only the fields intended for the operation.
|
||||||
|
|
||||||
|
Unsafe:
|
||||||
|
|
||||||
|
```php
|
||||||
|
Post::create($request->all());
|
||||||
|
```
|
||||||
|
|
||||||
|
Preferred:
|
||||||
|
|
||||||
|
```php
|
||||||
|
$post = Post::create($request->safe()->only(['title', 'body']));
|
||||||
|
```
|
||||||
|
|
||||||
|
Validated data is not automatically safe for mass assignment. Keep model `$fillable` or `$guarded` rules aligned with the operation, and never add a sensitive attribute to validation only to make mass assignment convenient.
|
||||||
|
|
||||||
|
## Express conditional rules clearly
|
||||||
|
|
||||||
|
Use conditional rules such as `Rule::when()`, `required_if`, or `exclude_unless` when they make the condition explicit. Choose the simplest form that remains easy to test.
|
||||||
|
|
||||||
|
```php
|
||||||
|
'company_name' => [
|
||||||
|
'string',
|
||||||
|
'max:255',
|
||||||
|
Rule::when(
|
||||||
|
$this->input('account_type') === 'business',
|
||||||
|
['required'],
|
||||||
|
['nullable'],
|
||||||
|
),
|
||||||
|
],
|
||||||
|
```
|
||||||
|
|
||||||
|
## Add cross-field validation after base rules
|
||||||
|
|
||||||
|
Use a form request's `after()` method for validation that depends on multiple fields or application state. Skip expensive queries when prerequisite fields already failed validation.
|
||||||
|
|
||||||
|
```php
|
||||||
|
public function after(): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
function (Validator $validator) {
|
||||||
|
if ($validator->errors()->hasAny(['product_id', 'quantity'])) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$stock = Product::find($this->integer('product_id'))?->stock;
|
||||||
|
|
||||||
|
if ($stock !== null && $this->integer('quantity') > $stock) {
|
||||||
|
$validator->errors()->add('quantity', 'Not enough stock.');
|
||||||
|
}
|
||||||
|
},
|
||||||
|
];
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Validation against mutable state does not prevent a race between validation and persistence. Enforce inventory, uniqueness, and similar invariants with database constraints, atomic updates, or a database transaction as appropriate.
|
||||||
@@ -0,0 +1,96 @@
|
|||||||
|
---
|
||||||
|
name: tailwindcss-development
|
||||||
|
description: "Always invoke when the user's message includes 'tailwind' in any form. Also invoke for: building responsive grid layouts (multi-column card grids, product grids), flex/grid page structures (dashboards with sidebars, fixed topbars, mobile-toggle navs), styling UI components (cards, tables, navbars, pricing sections, forms, inputs, badges), adding dark mode variants, fixing spacing or typography, and Tailwind v3/v4 work. The core use case: writing or fixing Tailwind utility classes in HTML templates (Blade, JSX, Vue). Skip for backend PHP logic, database queries, API routes, JavaScript with no HTML/CSS component, CSS file audits, build tool configuration, and vanilla CSS."
|
||||||
|
license: MIT
|
||||||
|
metadata:
|
||||||
|
author: laravel
|
||||||
|
---
|
||||||
|
|
||||||
|
# Tailwind CSS development
|
||||||
|
|
||||||
|
## Documentation
|
||||||
|
|
||||||
|
Use `search-docs` for detailed Tailwind CSS v4 patterns and documentation.
|
||||||
|
|
||||||
|
## Basic usage
|
||||||
|
|
||||||
|
- Use Tailwind CSS classes to style HTML. Before introducing new patterns, check and follow the project's existing Tailwind conventions.
|
||||||
|
- Offer to extract repeated patterns into components that match the project's conventions, such as Blade, JSX, or Vue components.
|
||||||
|
- Consider class placement, order, priority, and defaults. Remove redundant classes, add classes to parent or child elements carefully to reduce repetition, and group elements logically.
|
||||||
|
|
||||||
|
## Tailwind CSS v4 specifics
|
||||||
|
|
||||||
|
- Always use Tailwind CSS v4 and avoid deprecated utilities.
|
||||||
|
- `corePlugins` is not supported in Tailwind v4.
|
||||||
|
|
||||||
|
### CSS-first configuration
|
||||||
|
|
||||||
|
In Tailwind v4, you configure Tailwind in CSS with the `@theme` directive. You don't need a separate `tailwind.config.js` file:
|
||||||
|
|
||||||
|
<!-- CSS-First Config -->
|
||||||
|
```css
|
||||||
|
@theme {
|
||||||
|
--color-brand: oklch(0.72 0.11 178);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Import syntax
|
||||||
|
|
||||||
|
In Tailwind v4, import Tailwind with a regular CSS `@import` statement instead of the `@tailwind` directives used in v3:
|
||||||
|
|
||||||
|
<!-- v4 Import Syntax -->
|
||||||
|
```diff
|
||||||
|
- @tailwind base;
|
||||||
|
- @tailwind components;
|
||||||
|
- @tailwind utilities;
|
||||||
|
+ @import "tailwindcss";
|
||||||
|
```
|
||||||
|
|
||||||
|
### Replaced utilities
|
||||||
|
|
||||||
|
Tailwind v4 removed deprecated utilities. Use the replacements shown below. For opacity, drop the `*-opacity-*` class and append the value as a modifier on the existing color: `bg-blue-500 bg-opacity-50` becomes `bg-blue-500/50`, `text-white text-opacity-75` becomes `text-white/75`.
|
||||||
|
|
||||||
|
| Deprecated | Replacement |
|
||||||
|
|------------|-------------|
|
||||||
|
| bg-opacity-* | bg-{color}/* |
|
||||||
|
| text-opacity-* | text-{color}/* |
|
||||||
|
| border-opacity-* | border-{color}/* |
|
||||||
|
| divide-opacity-* | divide-{color}/* |
|
||||||
|
| ring-opacity-* | ring-{color}/* |
|
||||||
|
| placeholder-opacity-* | placeholder-{color}/* |
|
||||||
|
| flex-shrink-* | shrink-* |
|
||||||
|
| flex-grow-* | grow-* |
|
||||||
|
| overflow-ellipsis | text-ellipsis |
|
||||||
|
| decoration-slice | box-decoration-slice |
|
||||||
|
| decoration-clone | box-decoration-clone |
|
||||||
|
|
||||||
|
## Spacing
|
||||||
|
|
||||||
|
Use `gap` utilities instead of margins for spacing between siblings:
|
||||||
|
|
||||||
|
<!-- Gap Utilities -->
|
||||||
|
```html
|
||||||
|
<div class="flex gap-8">
|
||||||
|
<div>Item 1</div>
|
||||||
|
<div>Item 2</div>
|
||||||
|
</div>
|
||||||
|
```
|
||||||
|
|
||||||
|
## Dark mode
|
||||||
|
|
||||||
|
If existing pages and components support dark mode, new pages and components must support it the same way, typically using the `dark:` variant:
|
||||||
|
|
||||||
|
<!-- Dark Mode -->
|
||||||
|
```html
|
||||||
|
<div class="bg-white dark:bg-gray-900 text-gray-900 dark:text-white">
|
||||||
|
Content adapts to color scheme
|
||||||
|
</div>
|
||||||
|
```
|
||||||
|
|
||||||
|
## Common pitfalls
|
||||||
|
|
||||||
|
- Using deprecated v3 utilities, such as `bg-opacity-*` and `flex-shrink-*`
|
||||||
|
- Using `@tailwind` directives instead of `@import "tailwindcss"`
|
||||||
|
- Using `tailwind.config.js` instead of the CSS `@theme` directive
|
||||||
|
- Using margins for spacing between siblings instead of gap utilities
|
||||||
|
- Forgetting to add dark mode variants when the project uses dark mode
|
||||||
@@ -0,0 +1,57 @@
|
|||||||
|
---
|
||||||
|
name: testing-best-practices
|
||||||
|
description: "Laravel test design and review. Use when selecting coverage, naming or structuring tests, choosing assertions or test data, isolating dependencies, testing HTTP or security boundaries, improving suite performance, or reviewing test value. Use framework guidance or search-docs for Pest and PHPUnit syntax."
|
||||||
|
license: MIT
|
||||||
|
metadata:
|
||||||
|
author: laravel
|
||||||
|
---
|
||||||
|
|
||||||
|
# Testing best practices
|
||||||
|
|
||||||
|
This skill provides rules for designing Laravel tests. Each rule file explains what to do and why. Use `search-docs` for Laravel API syntax. Fetch the PHPUnit 12.5.42 documentation at `https://phpunit.de/documentation.html` for PHPUnit API syntax.
|
||||||
|
This project uses PHPUnit. Follow the corresponding guidance in each rule.
|
||||||
|
|
||||||
|
## Consistency first
|
||||||
|
|
||||||
|
Read nearby tests before you choose syntax and organization.
|
||||||
|
|
||||||
|
A pattern repeated throughout the project is a convention, and project conventions take precedence over this skill. Follow them and give new tests the same structure.
|
||||||
|
|
||||||
|
These rules govern the tests you write now. An existing test that follows a project convention is not defective merely because it conflicts with this skill. Do not delete or rewrite it. If the convention has drawbacks, explain them and let the user decide.
|
||||||
|
|
||||||
|
## What to test
|
||||||
|
|
||||||
|
Read this section before you write a test.
|
||||||
|
|
||||||
|
- Test observable behavior and application contracts. A test must pass after an implementation change if the behavior stays the same.
|
||||||
|
- Cover every changed decision and each applicable high-value failure mode. A decision is a branch, a validation, a calculation, or an authorization.
|
||||||
|
- Exercise declarations through behavior instead of repeating their text.
|
||||||
|
- Leave framework behavior to framework tests. Testing project configuration is not testing the framework. A constrained relationship, cast, scope, or validation rule belongs to this project.
|
||||||
|
- Keep every test that can detect a distinct defect. When two tests detect the same defect, trim the higher-layer test to one case and report the duplication. Do not delete an existing test.
|
||||||
|
- Write a feature test first. Write a unit test only for logic that does not use the framework.
|
||||||
|
- Write a feature test for every behavior reachable through a request. Real-browser tests require `laravel/dusk` and a browser download, neither of which this project installs. Mention the package only if the user asks for a real-browser test.
|
||||||
|
- Use the test tools that the project installs. Add a new test dependency, plugin, or browser only after the user asks for it.
|
||||||
|
|
||||||
|
## How to apply
|
||||||
|
|
||||||
|
1. Read the code under test. Read the tests in the same directory. Identify every decision in the code.
|
||||||
|
2. Select every applicable branch in the rule index. Read every selected rule file.
|
||||||
|
3. Report each defect in the code before you write a test. Examples are a method with no body, a policy that no action calls, and a write action with no validation. Test the actual behavior. Report the defect to the user.
|
||||||
|
4. Write the tests. Run the smallest set of tests that covers the change. The tests must pass.
|
||||||
|
5. Check every applicable item in `rules/review.md` and every selected rule file. Resolve every mismatch before completion.
|
||||||
|
|
||||||
|
## Rule index
|
||||||
|
|
||||||
|
Most changes need more than one rule file.
|
||||||
|
|
||||||
|
| Subject | Rule file |
|
||||||
|
| --- | --- |
|
||||||
|
| Test framework features that may already do the work | [`rules/finding-features.md`](rules/finding-features.md) |
|
||||||
|
| File layout, test names, and groups | [`rules/naming.md`](rules/naming.md) |
|
||||||
|
| Arrange-act-assert and choosing the correct assertion | [`rules/assertions.md`](rules/assertions.md) |
|
||||||
|
| Endpoint coverage, authentication, authorization, tenant isolation, validation, and browser tests | [`rules/endpoint-tests.md`](rules/endpoint-tests.md) |
|
||||||
|
| Factories, test data ownership, and repeated input values | [`rules/test-data.md`](rules/test-data.md) |
|
||||||
|
| Fakes, mocks, outbound HTTP, time, randomness, and databases | [`rules/isolation.md`](rules/isolation.md) |
|
||||||
|
| Escaping, injection, cross-tenant access, and privilege checks | [`rules/security.md`](rules/security.md) |
|
||||||
|
| Environment and CI settings for a slow suite | [`rules/performance.md`](rules/performance.md) |
|
||||||
|
| Reviewing a test or suite | [`rules/review.md`](rules/review.md) |
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
# Assertions
|
||||||
|
|
||||||
|
## Arrange, act, assert
|
||||||
|
|
||||||
|
Write each test in three parts: setup, one action, and assertions. Put one blank line between them so readers can identify each part without comments.
|
||||||
|
|
||||||
|
Keep each test self-contained. Do not use values created by another test.
|
||||||
|
|
||||||
|
## How to find the correct assertion
|
||||||
|
|
||||||
|
First identify the subject of the check, then find an assertion designed for it. A subject-specific assertion identifies the incorrect value when the test fails.
|
||||||
|
|
||||||
|
1. Search Laravel's assertions for framework subjects such as responses, the database, sessions, models, queues, events, mail, and notifications.
|
||||||
|
2. Fetch the PHPUnit 12.5.42 documentation at `https://phpunit.de/documentation.html` for the assertions of PHPUnit for a plain value, a type, a format, or a shape.
|
||||||
|
3. Build the check by hand only if no assertion exists for the subject.
|
||||||
|
4. Confirm the name in the documentation before you use it. Do not write an assertion that you did not confirm.
|
||||||
|
|
||||||
|
Use the assertion in this table for each subject.
|
||||||
|
|
||||||
|
| Subject | Assertion to use |
|
||||||
|
| --- | --- |
|
||||||
|
| A return value, the state of an object, or a transformation of a value | `assertSame()`, or the assertion for the type |
|
||||||
|
| An HTTP status, JSON, a session, or Inertia | a Laravel response assertion |
|
||||||
|
| The state in the database | a Laravel database assertion |
|
||||||
|
| The existence of a model | `assertModelExists($model)` rather than `assertDatabaseHas('users', ['id' => $user->id])` |
|
||||||
|
|
||||||
|
Use `assertSame()` and not `assertEquals()`, because `assertSame()` also compares the type.
|
||||||
|
|
||||||
|
Assert each fact once, but status and content are separate facts. `assertSee` passes on an error page that contains the text, so keep `assertOk()` alongside it when the status is part of the behavior.
|
||||||
|
|
||||||
|
## Named response assertions
|
||||||
|
|
||||||
|
Use a named response assertion, such as `assertNotFound()`, rather than `assertStatus(404)`. A failure then identifies the broken contract. Laravel provides named assertions for commonly tested status codes.
|
||||||
|
|
||||||
|
Group the assertions for one subject together. Start a new group when the subject changes.
|
||||||
|
|
||||||
|
## Assert a known value
|
||||||
|
|
||||||
|
Write the expected value in the test, or calculate the expected value by a different method. Do not calculate the expected value with the logic of the implementation, because the test then passes when that logic is wrong.
|
||||||
|
|
||||||
|
```php
|
||||||
|
// The test calculates the value with the logic of the implementation...
|
||||||
|
$expected = now()->subHours(24)->floorSeconds(30)->toJson();
|
||||||
|
$this->assertSame($expected, $from);
|
||||||
|
|
||||||
|
// The test sets a fixed input and asserts a known value...
|
||||||
|
$this->travelTo('2025-01-01 00:00:00');
|
||||||
|
$this->assertSame('2024-12-31T00:00:00.000000Z', $from);
|
||||||
|
```
|
||||||
|
|
||||||
|
## Assert the complete result
|
||||||
|
|
||||||
|
A status code is not the complete result of a write operation. Assert each of the following if the operation changes it:
|
||||||
|
|
||||||
|
- The response or the return value.
|
||||||
|
- The state in the database.
|
||||||
|
- The jobs and the events that the operation dispatches.
|
||||||
|
- The notifications and the mail that the operation sends.
|
||||||
|
|
||||||
|
On the failure path, assert that the operation makes none of these changes. A test that asserts only `assertOk()` passes even when the application saves no record.
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
# Endpoint tests
|
||||||
|
|
||||||
|
## How to write the test
|
||||||
|
|
||||||
|
Fetch `https://laravel.com/framework/docs/http-tests` for the request helpers, the authentication helpers, and the response assertions. Confirm the name before you use it, and do not guess an assertion.
|
||||||
|
|
||||||
|
Choose an assertion based on the subject of the check: the status, a header, a redirect, the JSON body, the session, a validation error, or the view. Laravel provides a named assertion for each subject that identifies the incorrect value.
|
||||||
|
|
||||||
|
## Endpoint coverage
|
||||||
|
|
||||||
|
Write a test for each applicable case:
|
||||||
|
|
||||||
|
- The request has missing or invalid authentication.
|
||||||
|
- The request comes from a different tenant, team, or organization.
|
||||||
|
- The user has an insufficient role or permission.
|
||||||
|
- The request does not satisfy a route or scope constraint.
|
||||||
|
- The request fails the validation.
|
||||||
|
- The request is valid. Assert both the response and the persisted state.
|
||||||
|
|
||||||
|
Assert the application's actual behavior rather than a generic status code. An API returns `401` for a missing or invalid token, while a browser endpoint redirects to the sign-in route.
|
||||||
|
|
||||||
|
## Tenant isolation
|
||||||
|
|
||||||
|
Assert the status code returned for a cross-tenant request. Use `404` rather than `403` when one tenant must not learn that another tenant's record exists, because `403` confirms its existence.
|
||||||
|
|
||||||
|
## Test authorization at the policy level
|
||||||
|
|
||||||
|
An HTTP test shows that the endpoint performs authorization. It cannot identify which mechanism refused the request because middleware, a policy, and a call to `abort()` can all return `403`.
|
||||||
|
|
||||||
|
- Assert the complete matrix of the permissions against the policy or the gate. A failure then names the rule that is not correct.
|
||||||
|
- Write one HTTP test for one refused role, which shows that the endpoint calls the authorization.
|
||||||
|
- If the project has a helper that asserts the ability and the arguments of the gate, use that helper.
|
||||||
|
|
||||||
|
## Testing validation
|
||||||
|
|
||||||
|
- Write one test for each validation rule when each failure represents a separate contract.
|
||||||
|
- Write one test with an empty payload to assert several required fields together.
|
||||||
|
- Assert the text of the message that the user gets. A message that is present but wrong is a defect.
|
||||||
|
- Use a data provider with the `#[DataProvider]` attribute for input values that need the same setup and the same assertions. Use the `#[TestWith]` attribute for a small set of values.
|
||||||
|
|
||||||
|
Send an input value that is not valid through the application, and assert the error. Do not assert that an array of rules contains a string, because that assertion tests the declaration and not the behavior. Use such an assertion only for a rule that no request can reach, and write the reason in the test.
|
||||||
|
|
||||||
|
### Which layer owns which case
|
||||||
|
|
||||||
|
The rule-class test owns the matrix of values that pass and fail. The endpoint test proves that the endpoint applies the rule and that the user receives the message.
|
||||||
|
|
||||||
|
When both tests contain the matrix, move it to the rule-class test and retain one case in the endpoint test. Never remove the last case, because the rule-class test still passes if the request omits the rule. The same division applies to policies, scopes, and other classes called by a request.
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
# How to find test framework features
|
||||||
|
|
||||||
|
PHPUnit and Laravel provide features for most testing needs. Find an existing feature before implementing the behavior by hand.
|
||||||
|
|
||||||
|
- Give `search-docs` the capability you need rather than the name of a method you remember. It returns Laravel testing documentation for the installed version.
|
||||||
|
- Fetch `https://phpunit.de/documentation.html` for version-specific PHPUnit attributes, assertions, and command-line options.
|
||||||
|
- If a search returns no results, tell the user that the installed version does not provide the feature. Do not write an API that you have not confirmed.
|
||||||
|
|
||||||
|
Search for a feature in this table before you write the code by hand.
|
||||||
|
|
||||||
|
| Work that you need | Term to search for |
|
||||||
|
| --- | --- |
|
||||||
|
| Run one test method with many input values | data provider, `#[DataProvider]`, `#[TestWith]` |
|
||||||
|
| Run one test only after another test passes | `#[Depends]` |
|
||||||
|
| Select or skip a set of tests in one run | `#[Group]`, `--group`, `--exclude-group` |
|
||||||
|
| Skip a test on a version or on a missing extension | `#[RequiresPhp]`, `#[RequiresPhpExtension]` |
|
||||||
|
| Find a test that depends on the order of the run | `--order-by=random` |
|
||||||
|
| Reduce the time of a slow suite | ParaTest, `--cache-result` |
|
||||||
|
| Stop the run at the first failure while you debug | `--stop-on-failure`, `--filter` |
|
||||||
|
|
||||||
|
## Built-in Laravel assertion methods
|
||||||
|
|
||||||
|
Laravel provides assertions for each part of the framework. Fetch `https://laravel.com/framework/docs/testing` for the complete list, and search for an assertion before you build a check by hand. Examples include `assertDatabaseHas()`, `assertModelExists()`, `assertSoftDeleted()`, response assertions such as `assertRedirectToRoute()` and `assertJsonPath()`, and fake assertions such as `Queue::assertPushed()` and `Notification::assertSentTo()`.
|
||||||
|
|
||||||
|
A hand-built check fails with `false is not true`. That message identifies nothing. A framework assertion names the incorrect table, value, or response, so the failure shows what to fix.
|
||||||
|
|
||||||
|
```php
|
||||||
|
// The failure says that false is not true. Instead of this...
|
||||||
|
$this->assertTrue(User::where('email', 'taylor@laravel.com')->exists());
|
||||||
|
|
||||||
|
// Use this... the failure names the table and the attributes that it did not find...
|
||||||
|
$this->assertDatabaseHas('users', ['email' => 'taylor@laravel.com']);
|
||||||
|
```
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
# Fakes, mocks, and determinism
|
||||||
|
|
||||||
|
Tests that depend on actual time, randomness, sleeping, or network calls can fail for reasons unrelated to the code under test. Control all four.
|
||||||
|
|
||||||
|
## How to isolate a dependency
|
||||||
|
|
||||||
|
Fetch `https://laravel.com/framework/docs/mocking` for Laravel's fakes, facade doubles, and fake assertions. Confirm each name before using it.
|
||||||
|
|
||||||
|
Identify the dependency, then choose the first option that applies. A framework fake preserves the real code path, while a mock replaces the dependency.
|
||||||
|
|
||||||
|
1. Always use framework fakes for facades such as events, queues, mail, notifications, storage, the HTTP client, time, and sleep.
|
||||||
|
2. Use a developer-defined fake implementation of a service if the application provides one.
|
||||||
|
3. Use a mock for a container-resolved contract only when the real implementation leaves the process or is nondeterministic.
|
||||||
|
4. Use the real implementation for everything else, including the database.
|
||||||
|
|
||||||
|
## Framework fakes
|
||||||
|
|
||||||
|
- Create each fake inside the test method that needs it. Do not create fakes in `setUp()`.
|
||||||
|
- Pass class names to `Event::fake()` and `Queue::fake()` when you know which classes the code dispatches. A fake without class names can hide an unexpected dispatch.
|
||||||
|
- Use a fake without class names only when the test asserts the complete result, including a call to `assertNothingPushed()`.
|
||||||
|
- Write one assertion for each fake. The assertion states that the code dispatches the item, or that the code does not dispatch the item.
|
||||||
|
- If the data of a job or an event is part of the behavior, assert that data.
|
||||||
|
- Use `Exceptions::fake()` to assert that the application reports the correct exception. Do not use `withoutExceptionHandling()`, because it changes the response under test.
|
||||||
|
|
||||||
|
Create prerequisite factory records before calling `Event::fake()`. Factories use model events, such as a `creating` hook that generates a UUID. A fake without class names suppresses those events, and the factory can then produce an invalid model. Call the fake first only when a factory event is under test, and pass that event's class name.
|
||||||
|
|
||||||
|
## Mocking
|
||||||
|
|
||||||
|
Use `shouldReceive()` before the action to declare an expectation. Use `shouldHaveReceived()` after the action for a spy. If an equality check cannot state the expected argument, such as a check of one field of a value object, use `Mockery::on()` or `withArgs()`.
|
||||||
|
|
||||||
|
Use `$this->mock(Contract::class)` to put a mock in the container. Do not build a PHPUnit mock for a class that Mockery can double, because the project uses Mockery.
|
||||||
|
|
||||||
|
## Outbound HTTP testing
|
||||||
|
|
||||||
|
Call `Http::preventStrayRequests()`. Any request without a matching fake then fails without reaching the network.
|
||||||
|
|
||||||
|
Fake the exact endpoint that each test calls. Do not call `Http::fake()` without an endpoint, because a fake without an endpoint accepts unexpected requests and can hide defects.
|
||||||
|
|
||||||
|
## Time and randomness
|
||||||
|
|
||||||
|
- Freeze the time or move the time in each test that depends on a date, a period, or a timestamp.
|
||||||
|
- Use the framework helpers `$this->freezeTime()`, `$this->travelTo()`, `$this->travel()`, and `$this->travelBack()`. Do not call `Carbon::setTestNow()`.
|
||||||
|
- If the test asserts an identifier or a slug, use `Str::createRandomStringsUsing()` to fix the generated string.
|
||||||
|
- Use `Sleep::fake()` instead of a real sleep, and assert the sleeps that the code requests.
|
||||||
|
- If the suite does not restore the time and the randomness for every test, restore them after each test.
|
||||||
|
|
||||||
|
## Database
|
||||||
|
|
||||||
|
- Run real queries against the real records in the test database. Do not mock the query builder, because the test then asserts the mock.
|
||||||
|
- If the shape of the serialized model is a contract, assert the exact keys of `toArray()`. The test then fails when the model exposes a new attribute.
|
||||||
|
- Test application behavior caused by the schema, such as deleting dependent records through a cascade. Do not test the database engine's cascade implementation.
|
||||||
|
- Use `LazilyRefreshDatabase` instead of `RefreshDatabase`. A test that does not use the database then does not run the migrations.
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
# Naming and structure
|
||||||
|
|
||||||
|
## File layout
|
||||||
|
|
||||||
|
- Name each test file `{ClassName}Test.php`.
|
||||||
|
- Place each test file at the same relative path as the class under test. The class `app/Actions/DeleteTeam.php` gets the test `tests/Unit/Actions/DeleteTeamTest.php`.
|
||||||
|
- Follow the project's convention for fixture files. If none exists, put fixtures in `tests/Fixtures/` and load them by path.
|
||||||
|
- Move large literal values out of the test body and into fixture files.
|
||||||
|
|
||||||
|
## Test class and methods
|
||||||
|
|
||||||
|
- Extend the base `TestCase` of the project in each feature test class.
|
||||||
|
- Extend `PHPUnit\Framework\TestCase` in each unit test class, as the stub of `php artisan make:test --unit` does. A unit test covers logic that does not use the framework, so it does not boot the application.
|
||||||
|
- Give each test method the prefix `test_`, or add the `#[Test]` attribute to the method. Use the convention of the other files in the same directory.
|
||||||
|
|
||||||
|
## Naming tests
|
||||||
|
|
||||||
|
The name of a test method is a specification. Separate the words with underscores. State the user-visible result and the condition that causes it.
|
||||||
|
|
||||||
|
- Name the behavior, not the method under test. The file name already gives the class.
|
||||||
|
- Give the exact status code in the name of a test for an API error.
|
||||||
|
- Do not write `given`, `when`, or `then` in the name.
|
||||||
|
|
||||||
|
```php
|
||||||
|
public function test_unauthenticated_request_redirects_to_login(): void { ... }
|
||||||
|
public function test_returns_401_when_no_token_is_provided(): void { ... }
|
||||||
|
public function test_valid_payload_creates_record_and_returns_201(): void { ... }
|
||||||
|
```
|
||||||
|
|
||||||
|
Use a verb that describes a result, such as `returns`, `renders`, `creates`, `dispatches`, `rejects`, `forbids`, `falls back`, or `does not`.
|
||||||
|
|
||||||
|
Do not write `test_store()`, `test_it_works()`, or `test_validation()`, because none of them gives a result.
|
||||||
|
|
||||||
|
## Grouping
|
||||||
|
|
||||||
|
Write one test class for each class under test. If one file covers separate actions in a lifecycle, write a separate test class for each action, such as `StoreOrderControllerTest` and `UpdateOrderControllerTest`.
|
||||||
|
|
||||||
|
Use the `#[Group]` attribute to mark the tests that a run must select or must skip. Do not use a group to give structure to a file, because a class gives the structure.
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
# Test suite performance
|
||||||
|
|
||||||
|
These settings apply to the project and CI, not to individual tests. Read `rules/isolation.md` for choices within a test.
|
||||||
|
|
||||||
|
Fetch the PHPUnit 12.5.42 documentation at `https://phpunit.de/documentation.html` for PHPUnit options that make test runs faster.
|
||||||
|
Verify each flag in the documentation before adding it to CI.
|
||||||
|
|
||||||
|
Measure before changing a setting. Find the slow test first, and apply a project-wide setting only after identifying the costly work.
|
||||||
|
|
||||||
|
## Test environment
|
||||||
|
|
||||||
|
- Set `BCRYPT_ROUNDS=4` in `.env.testing` or in `phpunit.xml`. The default value is 12, and the hash then takes most of the time of each test that signs a user in.
|
||||||
|
- Disable Xdebug. Unless the run needs coverage, disable pcov too.
|
||||||
|
- Disable packages that perform work on every request in the test environment. Examples are Pulse, Telescope, and Nightwatch.
|
||||||
|
- Use the `WithCachedConfig` and `WithCachedRoutes` traits, so the run does not parse the configuration and the routes for every test.
|
||||||
|
- Call `withoutVite()`, or `withoutMix()`, so the framework does not resolve a built asset.
|
||||||
|
|
||||||
|
## Global fakes
|
||||||
|
|
||||||
|
Put these three calls in the `setUp()` of the base `TestCase` of the project:
|
||||||
|
|
||||||
|
- `Http::preventStrayRequests()`, because one request that reaches the network can slow the suite. It catches requests that go through Laravel's HTTP client. Check direct Guzzle and cURL usage separately.
|
||||||
|
- `Sleep::fake(syncWithCarbon: true)`, so a retry and a backoff do not sleep.
|
||||||
|
- `Exceptions::fake()`, so the suite does not report an exception to an external service.
|
||||||
|
|
||||||
|
## How to run the suite in parallel
|
||||||
|
|
||||||
|
Run `php artisan test --parallel`, which uses ParaTest, to spread tests across the machine's CPU cores. If the default count does not suit the machine or CI, add `--processes=N`.
|
||||||
|
|
||||||
|
A parallel run gives each process a separate database. Each test must meet the conditions below. A test that fails only in parallel breaks one of them.
|
||||||
|
|
||||||
|
- The test creates each record that it reads. It does not read a record that another test creates.
|
||||||
|
- The test does not depend on the order of the run.
|
||||||
|
- The test does not share a file, a cache key, or a queue with another test. Give each process a separate name for such a resource.
|
||||||
|
|
||||||
|
## How to find a slow test
|
||||||
|
|
||||||
|
Run `php artisan test --profile` to list the slowest tests. Start with the ten slowest tests, because the same cause often applies to the complete suite.
|
||||||
|
|
||||||
|
If the cause of a slow test is unclear, add an event listener or temporary log entry to identify the work the test does.
|
||||||
|
|
||||||
|
## Common errors
|
||||||
|
|
||||||
|
- The run loads Xdebug for a test that does not need it.
|
||||||
|
- `BCRYPT_ROUNDS` keeps the default value, because the project has no `.env.testing`.
|
||||||
|
- The code under test calls the real `sleep()`, and `Sleep::fake()` then does not help.
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
# Reviewing tests
|
||||||
|
|
||||||
|
Check every item in this file. A test can pass and still provide no value. For each test, identify the defect it would catch.
|
||||||
|
|
||||||
|
Report each finding. Do not delete or rewrite a test without the user's approval. If an issue appears throughout the suite as a convention, report the pattern once rather than once for each affected file.
|
||||||
|
|
||||||
|
## Test value
|
||||||
|
|
||||||
|
- [ ] Each test covers observable behavior or an application contract, and passes after a change to the implementation that keeps the behavior.
|
||||||
|
- [ ] Each tested declaration is exercised through behavior, and no test asserts the behavior of the framework. A test of what this project configures, such as a relation with a constraint, a cast, or a scope, belongs to this project.
|
||||||
|
- [ ] Each test detects a distinct defect that no other test covers. Reduce a duplicate at the higher layer to the one case that proves the wiring.
|
||||||
|
- [ ] Every changed decision and each applicable high-value failure mode has coverage.
|
||||||
|
|
||||||
|
## Names and structure
|
||||||
|
|
||||||
|
- [ ] Each file has the name `{ClassName}Test.php` and the relative path of the class under test.
|
||||||
|
- [ ] Each name states a result, the condition that causes it, and the status code for an API error.
|
||||||
|
- [ ] Each feature test class extends the base `TestCase` of the project, each unit test class extends `PHPUnit\Framework\TestCase`, and each file uses either the prefix `test_` or the `#[Test]` attribute consistently.
|
||||||
|
|
||||||
|
## Coverage
|
||||||
|
|
||||||
|
- [ ] HTTP tests cover authentication, authorization, role, scope, and validation when applicable.
|
||||||
|
- [ ] A request for a record of a different tenant gets a status code that does not confirm that the record exists.
|
||||||
|
- [ ] The complete permission matrix belongs in policy tests, not controller tests.
|
||||||
|
- [ ] Each validation rule has one test that asserts the user-visible message. If a unit test covers a matrix, reduce the duplicate higher-level coverage to one case rather than deleting it.
|
||||||
|
- [ ] Rendered user input and each dynamic part of a query have a security test.
|
||||||
|
|
||||||
|
## Data and determinism
|
||||||
|
|
||||||
|
- [ ] Each test creates its mutable records directly or through a helper that it calls, and every created record arranges the behavior or supports an assertion.
|
||||||
|
- [ ] `setUp()` holds configuration only.
|
||||||
|
- [ ] Each factory state and each relationship gives the meaning of the data.
|
||||||
|
- [ ] Each call to `make()` is in a test that does not need the database.
|
||||||
|
- [ ] Each test controls time, randomness, sleep, and outbound HTTP.
|
||||||
|
- [ ] Each test passes alone, and passes in the complete suite in any order.
|
||||||
|
|
||||||
|
## Assertions
|
||||||
|
|
||||||
|
- [ ] Each expected value is a known value, and the test does not calculate the value with the logic of the implementation.
|
||||||
|
- [ ] Each test of a write operation asserts the response, the state in the database, and the side effects.
|
||||||
|
- [ ] Each fake has one assertion, and gives the class names unless the test asserts the complete result.
|
||||||
|
- [ ] Each group of assertions stays on one subject, and each comparison uses `assertSame()`.
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
# Security tests
|
||||||
|
|
||||||
|
Test each security boundary where user input affects authorization, rendered output, or query construction. A defect at such a boundary is hard to detect, because the feature can keep working.
|
||||||
|
|
||||||
|
Write a test for each of these cases:
|
||||||
|
|
||||||
|
- **Cross-tenant access.** Request a record of a different tenant, team, or organization. Read `rules/endpoint-tests.md` for when the response should be `404` rather than `403`.
|
||||||
|
- **Each unprivileged role.** Use a data provider over the roles that the endpoint must refuse.
|
||||||
|
- **Escaping user-provided content.** Test escaping in HTML and mail. Include names and every free-text field a template renders. Assert that dangerous characters are escaped and the raw value is absent. Do not assert an exact entity for a quote, because Markdown and mail CSS inliners can decode it.
|
||||||
|
- **Injection into dynamic query components.** Examples include sort columns, filter fields, and sort directions.
|
||||||
|
- **An unexpected key** in a payload or configuration array. A merge that accepts every key can set an attribute the user must not control.
|
||||||
|
|
||||||
|
```php
|
||||||
|
public function test_escapes_dangerous_content_in_the_notification(): void
|
||||||
|
{
|
||||||
|
$organization = Organization::factory()->make([
|
||||||
|
'name' => "O'Reilly <script>alert('xss')</script>",
|
||||||
|
]);
|
||||||
|
|
||||||
|
$content = (new QuotaApproaching($organization, 80))->toMail()->render();
|
||||||
|
|
||||||
|
$this->assertStringContainsString('<script>', $content);
|
||||||
|
$this->assertStringNotContainsString("<script>alert('xss')</script>", $content);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Laravel provides defenses against mass assignment, unauthorized access, and unescaped output. Test that the application applies the correct defense to each attribute, route, and template.
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
# Factories and test data
|
||||||
|
|
||||||
|
## Each test makes its own data
|
||||||
|
|
||||||
|
Create mutable records inside each test or through a private helper that the test calls. The setup then stays visible, and each test can select its factory state.
|
||||||
|
|
||||||
|
Use `setUp()` only for configuration that applies to every test in the class. Do not create records in it, because its objects remain in memory until the suite ends.
|
||||||
|
|
||||||
|
## Record construction
|
||||||
|
|
||||||
|
- Use `create()` if the test needs the record in the database.
|
||||||
|
- Use `make()` only if the test does not need the database. Examples include rendering a notification and testing a value object's behavior.
|
||||||
|
- Use a named factory state instead of a raw attribute. `User::factory()->unverified()->create()` gives the state meaning. `create(['email_verified_at' => null])` gives only its value.
|
||||||
|
- Use `for()` or the relationship helper of the project to declare the owner of a record.
|
||||||
|
- If several records must share one parent record, use `recycle()`.
|
||||||
|
- If several records need different attributes, use `sequence()`.
|
||||||
|
|
||||||
|
```php
|
||||||
|
$organization = Organization::factory()->onPlan(BillingPlan::PRO)->create();
|
||||||
|
|
||||||
|
$environment = Environment::factory()->recycle($organization)->create();
|
||||||
|
|
||||||
|
$organizations = Organization::factory()
|
||||||
|
->count(3)
|
||||||
|
->sequence(
|
||||||
|
['created_at' => now()->setSeconds(30)],
|
||||||
|
['created_at' => now()->setSeconds(1)],
|
||||||
|
)
|
||||||
|
->create();
|
||||||
|
```
|
||||||
|
|
||||||
|
Create only the records required to arrange the behavior or support an assertion.
|
||||||
|
|
||||||
|
## Data providers
|
||||||
|
|
||||||
|
Use a data provider when the setup, test body, and assertions remain the same across input values.
|
||||||
|
|
||||||
|
```php
|
||||||
|
public static function nonAdminRoles(): array
|
||||||
|
{
|
||||||
|
return collect(Role::cases())
|
||||||
|
->reject(fn (Role $role): bool => $role === Role::ADMIN)
|
||||||
|
->mapWithKeys(fn (Role $role): array => [$role->value => [$role]])
|
||||||
|
->all();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[DataProvider('nonAdminRoles')]
|
||||||
|
public function test_forbids_roles_other_than_admin(Role $role): void
|
||||||
|
{
|
||||||
|
$this->actingAs(User::factory()->hasOrganization($role)->create())
|
||||||
|
->post('/settings')
|
||||||
|
->assertForbidden();
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Declare each data provider method as `public static`.
|
||||||
|
|
||||||
|
Use parameterized tests for:
|
||||||
|
|
||||||
|
- enum cases
|
||||||
|
- roles and plans
|
||||||
|
- boundary values
|
||||||
|
- input values that are invalid in the same way
|
||||||
|
- input and output value pairs
|
||||||
|
|
||||||
|
If the cases need a different setup, a different behavior, or different assertions, write separate tests. One test function with a branch in the body is two tests in one function.
|
||||||
|
|
||||||
|
Give each data-provider case a key that states the difference. A failure then identifies the case without requiring you to count positions.
|
||||||
@@ -1,47 +1,148 @@
|
|||||||
<laravel-boost-guidelines>
|
<laravel-boost-guidelines>
|
||||||
# Laravel Application
|
=== foundation rules ===
|
||||||
|
|
||||||
This repository contains a Laravel application. Complete the following setup before working on the user's request.
|
# Laravel Boost Guidelines
|
||||||
|
|
||||||
## Prerequisites
|
## Foundational Context
|
||||||
|
|
||||||
Verify that PHP and Composer are available:
|
This application is a Laravel application running on PHP 8.5. Always use the APIs that match the installed major version of each package — do not assume a version.
|
||||||
|
|
||||||
```sh
|
Before relying on a package's API, confirm its installed version:
|
||||||
php -v
|
- PHP packages: run `composer show --direct` to list direct dependencies with versions, or `composer show <vendor/package>` for a single package.
|
||||||
composer -V
|
- JS packages: check `package.json` for the installed versions.
|
||||||
```
|
|
||||||
|
|
||||||
If either command is unavailable, detect the user's operating system and install the prerequisites with the appropriate command:
|
## Skills Activation
|
||||||
|
|
||||||
macOS:
|
This project has domain-specific skills available in `**/skills/**`. You MUST activate the relevant skill whenever you work in that domain—don't wait until you're stuck.
|
||||||
|
|
||||||
```sh
|
## Conventions
|
||||||
/bin/bash -c "$(curl -fsSL https://php.new/install/mac/8.5)"
|
|
||||||
```
|
|
||||||
|
|
||||||
Windows PowerShell:
|
- You must follow all existing code conventions used in this application. When creating or editing a file, check sibling files for the correct structure, approach, and naming.
|
||||||
|
- Use descriptive names for variables and methods. For example, `isRegisteredForDiscounts`, not `discount()`.
|
||||||
|
- Check for existing components to reuse before writing a new one.
|
||||||
|
|
||||||
```powershell
|
## Verification Scripts
|
||||||
Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; iex ((New-Object System.Net.WebClient).DownloadString('https://php.new/install/windows/8.5'))
|
|
||||||
```
|
|
||||||
|
|
||||||
Linux:
|
- Do not create verification scripts or tinker when tests cover that functionality and prove they work. Unit and feature tests are more important.
|
||||||
|
|
||||||
```sh
|
## Application Structure & Architecture
|
||||||
/bin/bash -c "$(curl -fsSL https://php.new/install/linux/8.5)"
|
|
||||||
```
|
|
||||||
|
|
||||||
After installation, ask the user to restart their terminal. If the agent needs the restarted shell to continue, ask the user to reopen their terminal and rerun their original prompt.
|
- Stick to existing directory structure; don't create new base folders without approval.
|
||||||
|
- Do not change the application's dependencies without approval.
|
||||||
|
|
||||||
## Agent Setup
|
## Frontend Bundling
|
||||||
|
|
||||||
Install Laravel Boost from the application root before making application changes:
|
- If a frontend change doesn't show in the UI or you get a "Unable to locate file in Vite manifest" error, run `npm run build` or ask the user to run `npm run dev` or `composer run dev`.
|
||||||
|
|
||||||
```sh
|
## Documentation Files
|
||||||
composer require laravel/boost --dev
|
|
||||||
php artisan boost:install
|
- You must only create documentation files if explicitly requested by the user.
|
||||||
```
|
|
||||||
|
=== boost rules ===
|
||||||
|
|
||||||
|
# Laravel Boost
|
||||||
|
|
||||||
|
## Tools
|
||||||
|
|
||||||
|
- Laravel Boost is an MCP server with tools designed specifically for this application. Prefer Boost tools over manual alternatives like shell commands or file reads.
|
||||||
|
- Use `database-query` to run read-only queries against the database instead of writing raw SQL in tinker.
|
||||||
|
- Use `database-schema` to inspect table structure before writing migrations or models.
|
||||||
|
- Use `get-absolute-url` to resolve the correct scheme, domain, and port for project URLs. Always use this before sharing a URL with the user.
|
||||||
|
- Use `browser-logs` to read browser logs, errors, and exceptions. Only recent logs are useful, ignore old entries.
|
||||||
|
|
||||||
|
## Searching Documentation (IMPORTANT)
|
||||||
|
|
||||||
|
- Use `search-docs` before changes that depend on Laravel ecosystem APIs, behavior, configuration, or version-specific syntax. Skip it for copy-only edits and other changes where package documentation is irrelevant. Reuse sufficient results already in context instead of searching again.
|
||||||
|
- Pass a `packages` array to scope results when you know which packages are relevant.
|
||||||
|
- Use multiple broad, topic-based queries: `['rate limiting', 'routing rate limiting', 'routing']`. Expect the most relevant results first.
|
||||||
|
- Do not add package names to queries because package info is already shared. Use `test resource table`, not `filament 4 test resource table`.
|
||||||
|
|
||||||
|
### Search Syntax
|
||||||
|
|
||||||
|
1. Use words for auto-stemmed AND logic: `rate limit` matches both "rate" AND "limit".
|
||||||
|
2. Use `"quoted phrases"` for exact position matching: `"infinite scroll"` requires adjacent words in order.
|
||||||
|
3. Combine words and phrases for mixed queries: `middleware "rate limit"`.
|
||||||
|
4. Use multiple queries for OR logic: `queries=["authentication", "middleware"]`.
|
||||||
|
|
||||||
|
## Project Rules
|
||||||
|
|
||||||
|
- This project contains committed, area-grouped rules in `.ai/rules` when that directory exists, including path-scoped framework guidelines under `.ai/rules/boost`. Before you enter plan mode or create/edit any file, you MUST first: open @.ai/rules/index.md (it maps file globs to rule files), read every rule file whose globs cover the path(s) in scope, and run `grep -rin 'keyword' .ai/rules` to catch what a path match alone misses. Do not write code until you have read and are following every matching rule. If `.ai/rules` does not exist, continue without it.
|
||||||
|
|
||||||
|
## Artisan
|
||||||
|
|
||||||
|
- Run Artisan commands directly via the command line (e.g., `php artisan route:list`). Use `php artisan list` to discover available commands and `php artisan [command] --help` to check parameters.
|
||||||
|
- Inspect routes with `php artisan route:list`. Filter with: `--method=GET`, `--name=users`, `--path=api`, `--except-vendor`, `--only-vendor`.
|
||||||
|
- Read configuration values using dot notation: `php artisan config:show app.name`, `php artisan config:show database.default`. Or read config files directly from the `config/` directory.
|
||||||
|
|
||||||
|
## Tinker
|
||||||
|
|
||||||
|
- Execute PHP in app context for debugging and testing code. Do not create models without user approval, prefer tests with factories instead. Prefer existing Artisan commands over custom tinker code.
|
||||||
|
- Always use single quotes to prevent shell expansion: `php artisan tinker --execute 'Your::code();'`
|
||||||
|
- Double quotes for PHP strings inside: `php artisan tinker --execute 'User::where("active", true)->count();'`
|
||||||
|
|
||||||
|
=== php rules ===
|
||||||
|
|
||||||
|
# PHP
|
||||||
|
|
||||||
|
- Always use curly braces for control structures, even for single-line bodies.
|
||||||
|
- Use PHP 8 constructor property promotion: `public function __construct(public GitHub $github) { }`. Do not leave empty zero-parameter `__construct()` methods unless the constructor is private.
|
||||||
|
- Use explicit return type declarations and type hints for all method parameters: `function isAccessible(User $user, ?string $path = null): bool`
|
||||||
|
- Use TitleCase for Enum keys: `FavoritePerson`, `BestLake`, `Monthly`.
|
||||||
|
- Prefer PHPDoc blocks over inline comments. Only add inline comments for exceptionally complex logic.
|
||||||
|
- Use array shape type definitions in PHPDoc blocks.
|
||||||
|
|
||||||
|
=== deployments rules ===
|
||||||
|
|
||||||
|
# Deployment
|
||||||
|
|
||||||
|
- Laravel can be deployed using [Laravel Cloud](https://cloud.laravel.com/), which is the fastest way to deploy and scale production Laravel applications.
|
||||||
|
- Activate the `deploying-to-cloud` skill whenever deploying to Laravel Cloud, configuring Cloud environments or resources, using the Cloud CLI, or troubleshooting Cloud deployments.
|
||||||
|
|
||||||
|
=== laravel/core rules ===
|
||||||
|
|
||||||
|
# Do Things the Laravel Way
|
||||||
|
|
||||||
|
- Use `php artisan make:` commands to create new files (i.e. migrations, controllers, models, etc.). You can list available Artisan commands using `php artisan list` and check their parameters with `php artisan [command] --help`.
|
||||||
|
- If you're creating a generic PHP class, use `php artisan make:class`.
|
||||||
|
- Pass `--no-interaction` to all Artisan commands to ensure they work without user input. You should also pass the correct `--options` to ensure correct behavior.
|
||||||
|
|
||||||
|
### Model Creation
|
||||||
|
|
||||||
|
- When creating new models, create useful factories and seeders for them too. Ask the user if they need any other things, using `php artisan make:model --help` to check the available options.
|
||||||
|
|
||||||
|
## APIs & Eloquent Resources
|
||||||
|
|
||||||
|
- For APIs, default to using Eloquent API Resources and API versioning unless existing API routes do not, then you should follow existing application convention.
|
||||||
|
|
||||||
|
## URL Generation
|
||||||
|
|
||||||
|
- When generating links to other pages, prefer named routes and the `route()` function.
|
||||||
|
|
||||||
|
## Testing
|
||||||
|
|
||||||
|
- When creating models for tests, use the factories for the models. Check if the factory has custom states that can be used before manually setting up the model.
|
||||||
|
- Faker: Use methods such as `$this->faker->word()` or `fake()->randomDigit()`. Follow existing conventions whether to use `$this->faker` or `fake()`.
|
||||||
|
- When creating tests, make use of `php artisan make:test [options] {name}` to create a feature test, and pass `--unit` to create a unit test. Most tests should be feature tests.
|
||||||
|
|
||||||
|
=== pint/core rules ===
|
||||||
|
|
||||||
|
# Laravel Pint Code Formatter
|
||||||
|
|
||||||
|
- If you have modified any PHP files, you must run `vendor/bin/pint --dirty --format agent` before finalizing changes to ensure your code matches the project's expected style.
|
||||||
|
- Do not run `vendor/bin/pint --test --format agent`, simply run `vendor/bin/pint --format agent` to fix any formatting issues.
|
||||||
|
|
||||||
|
=== phpunit/core rules ===
|
||||||
|
|
||||||
|
# PHPUnit
|
||||||
|
|
||||||
|
- This project uses PHPUnit. Create tests with `php artisan make:test --phpunit {name}`.
|
||||||
|
- Do not include the test suite directory in `{name}`. Use `SomeFeatureTest`, not `Feature/SomeFeatureTest`.
|
||||||
|
- Read the `testing-best-practices` skill for guidance on coverage, naming, structure, dependency isolation, and review.
|
||||||
|
|
||||||
|
## Running Tests
|
||||||
|
|
||||||
|
- Run the narrowest set of tests that covers the change. Pass a file path or `--filter=testName` to `php artisan test --compact`.
|
||||||
|
- Rerun a test after each change to it.
|
||||||
|
- Run `vendor/bin/phpunit` to call the test runner directly. It accepts the same file path and `--filter=testName` arguments.
|
||||||
|
|
||||||
Boost replaces these bootstrap instructions with guidelines tailored to the application. After installation, read `AGENTS.md` again and continue with the user's original request using the generated guidelines.
|
|
||||||
</laravel-boost-guidelines>
|
</laravel-boost-guidelines>
|
||||||
|
|||||||
@@ -0,0 +1,260 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Http\Controllers\Admin;
|
||||||
|
|
||||||
|
use App\Http\Controllers\Controller;
|
||||||
|
use App\Models\Category;
|
||||||
|
use App\Models\Product;
|
||||||
|
use App\Services\MakerWorldService;
|
||||||
|
use Illuminate\Http\JsonResponse;
|
||||||
|
use Illuminate\Http\RedirectResponse;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use Illuminate\View\View;
|
||||||
|
|
||||||
|
class MakerWorldController extends Controller
|
||||||
|
{
|
||||||
|
public function __construct(
|
||||||
|
public MakerWorldService $makerWorld
|
||||||
|
) {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Display the MakerWorld importer dashboard.
|
||||||
|
*/
|
||||||
|
public function index(Request $request): View
|
||||||
|
{
|
||||||
|
$isAuthenticated = $this->makerWorld->isAuthenticated();
|
||||||
|
$userProfile = $this->makerWorld->getUserProfile();
|
||||||
|
|
||||||
|
$tab = $request->query('tab', $isAuthenticated ? 'favorites' : 'community');
|
||||||
|
$models = [];
|
||||||
|
|
||||||
|
if ($tab === 'favorites' && $isAuthenticated) {
|
||||||
|
$models = $this->makerWorld->getFavorites();
|
||||||
|
} elseif ($tab === 'published' && $isAuthenticated) {
|
||||||
|
$models = $this->makerWorld->getPublished();
|
||||||
|
} elseif ($tab === 'community') {
|
||||||
|
$models = $this->makerWorld->getCommunityShowcase();
|
||||||
|
}
|
||||||
|
|
||||||
|
$importedProducts = Product::with('category')
|
||||||
|
->whereNotNull('makerworld_id')
|
||||||
|
->latest()
|
||||||
|
->paginate(15);
|
||||||
|
|
||||||
|
$importedIds = Product::whereNotNull('makerworld_id')
|
||||||
|
->pluck('makerworld_id')
|
||||||
|
->toArray();
|
||||||
|
|
||||||
|
$categories = Category::orderBy('name')->get();
|
||||||
|
|
||||||
|
return view('admin.makerworld.index', [
|
||||||
|
'isAuthenticated' => $isAuthenticated,
|
||||||
|
'userProfile' => $userProfile,
|
||||||
|
'currentTab' => $tab,
|
||||||
|
'models' => $models,
|
||||||
|
'importedProducts' => $importedProducts,
|
||||||
|
'importedIds' => $importedIds,
|
||||||
|
'categories' => $categories,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Authenticate with MakerWorld credentials.
|
||||||
|
*/
|
||||||
|
public function login(Request $request): RedirectResponse
|
||||||
|
{
|
||||||
|
$validated = $request->validate([
|
||||||
|
'account' => 'required|string',
|
||||||
|
'password' => 'required|string',
|
||||||
|
]);
|
||||||
|
|
||||||
|
$result = $this->makerWorld->loginWithCredentials(
|
||||||
|
$validated['account'],
|
||||||
|
$validated['password']
|
||||||
|
);
|
||||||
|
|
||||||
|
if ($result['status'] === 'success') {
|
||||||
|
return redirect()
|
||||||
|
->route('admin.makerworld.index', ['tab' => 'favorites'])
|
||||||
|
->with('success', $result['message']);
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($result['status'] === '2fa_required') {
|
||||||
|
return redirect()
|
||||||
|
->route('admin.makerworld.index')
|
||||||
|
->with('warning', $result['message'])
|
||||||
|
->with('makerworld_2fa_account', $result['account']);
|
||||||
|
}
|
||||||
|
|
||||||
|
return redirect()
|
||||||
|
->route('admin.makerworld.index')
|
||||||
|
->with('error', $result['message']);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Submit email verification code for 2FA.
|
||||||
|
*/
|
||||||
|
public function verifyCode(Request $request): RedirectResponse
|
||||||
|
{
|
||||||
|
$validated = $request->validate([
|
||||||
|
'account' => 'required|string',
|
||||||
|
'code' => 'required|string|size:6',
|
||||||
|
]);
|
||||||
|
|
||||||
|
$result = $this->makerWorld->verifyLoginCode(
|
||||||
|
$validated['account'],
|
||||||
|
$validated['code']
|
||||||
|
);
|
||||||
|
|
||||||
|
if ($result['status'] === 'success') {
|
||||||
|
return redirect()
|
||||||
|
->route('admin.makerworld.index', ['tab' => 'favorites'])
|
||||||
|
->with('success', $result['message']);
|
||||||
|
}
|
||||||
|
|
||||||
|
return redirect()
|
||||||
|
->route('admin.makerworld.index')
|
||||||
|
->with('error', $result['message'])
|
||||||
|
->with('makerworld_2fa_account', $validated['account']);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Save MakerWorld session / bearer token directly.
|
||||||
|
*/
|
||||||
|
public function saveToken(Request $request): RedirectResponse
|
||||||
|
{
|
||||||
|
$validated = $request->validate([
|
||||||
|
'token' => 'required|string|min:10',
|
||||||
|
]);
|
||||||
|
|
||||||
|
$this->makerWorld->setAccessToken($validated['token']);
|
||||||
|
|
||||||
|
return redirect()
|
||||||
|
->route('admin.makerworld.index', ['tab' => 'favorites'])
|
||||||
|
->with('success', 'MakerWorld token succesvol opgeslagen en verbonden!');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Disconnect MakerWorld account.
|
||||||
|
*/
|
||||||
|
public function disconnect(): RedirectResponse
|
||||||
|
{
|
||||||
|
$this->makerWorld->logout();
|
||||||
|
|
||||||
|
return redirect()
|
||||||
|
->route('admin.makerworld.index', ['tab' => 'community'])
|
||||||
|
->with('success', 'MakerWorld account succesvol ontkoppeld.');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Ajax preview endpoint for single model by URL or ID.
|
||||||
|
*/
|
||||||
|
public function preview(Request $request): JsonResponse
|
||||||
|
{
|
||||||
|
$input = $request->query('query');
|
||||||
|
|
||||||
|
if (! $input) {
|
||||||
|
return response()->json(['error' => 'Geen model URL of ID opgegeven.'], 400);
|
||||||
|
}
|
||||||
|
|
||||||
|
$id = $this->makerWorld->parseModelId($input);
|
||||||
|
|
||||||
|
if (! $id) {
|
||||||
|
return response()->json(['error' => 'Ongeldige MakerWorld URL of model-ID.'], 400);
|
||||||
|
}
|
||||||
|
|
||||||
|
$details = $this->makerWorld->getDesignDetails($id);
|
||||||
|
|
||||||
|
if (! $details) {
|
||||||
|
return response()->json(['error' => "Model #{$id} kon niet worden opgehaald bij MakerWorld."], 404);
|
||||||
|
}
|
||||||
|
|
||||||
|
$formatted = $this->makerWorld->formatDesignForImport($details);
|
||||||
|
$alreadyImported = Product::where('makerworld_id', $id)->first();
|
||||||
|
|
||||||
|
return response()->json([
|
||||||
|
'model' => $formatted,
|
||||||
|
'raw' => $details,
|
||||||
|
'is_imported' => (bool) $alreadyImported,
|
||||||
|
'existing_product' => $alreadyImported,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Import a single model into shop.
|
||||||
|
*/
|
||||||
|
public function import(Request $request): RedirectResponse|JsonResponse
|
||||||
|
{
|
||||||
|
$validated = $request->validate([
|
||||||
|
'makerworld_id' => 'required|integer',
|
||||||
|
'category_id' => 'nullable|exists:categories,id',
|
||||||
|
'custom_price' => 'nullable|numeric|min:0.5',
|
||||||
|
'custom_name' => 'nullable|string|max:255',
|
||||||
|
'is_active' => 'nullable|boolean',
|
||||||
|
]);
|
||||||
|
|
||||||
|
$details = $this->makerWorld->getDesignDetails($validated['makerworld_id']);
|
||||||
|
|
||||||
|
if (! $details) {
|
||||||
|
$msg = "Model #{$validated['makerworld_id']} kon niet worden opgehaald.";
|
||||||
|
if ($request->wantsJson()) {
|
||||||
|
return response()->json(['error' => $msg], 404);
|
||||||
|
}
|
||||||
|
|
||||||
|
return redirect()->back()->with('error', $msg);
|
||||||
|
}
|
||||||
|
|
||||||
|
$product = $this->makerWorld->importDesign(
|
||||||
|
$details,
|
||||||
|
$validated['category_id'] ?? null,
|
||||||
|
$validated['custom_price'] ?? null,
|
||||||
|
$validated['custom_name'] ?? null,
|
||||||
|
$request->boolean('is_active', true)
|
||||||
|
);
|
||||||
|
|
||||||
|
$msg = "Model \"{$product->name}\" is succesvol toegevoegd aan je webshop!";
|
||||||
|
|
||||||
|
if ($request->wantsJson()) {
|
||||||
|
return response()->json([
|
||||||
|
'success' => true,
|
||||||
|
'message' => $msg,
|
||||||
|
'product' => $product,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
return redirect()->back()->with('success', $msg);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Batch import multiple selected models.
|
||||||
|
*/
|
||||||
|
public function batchImport(Request $request): RedirectResponse
|
||||||
|
{
|
||||||
|
$validated = $request->validate([
|
||||||
|
'ids' => 'required|array',
|
||||||
|
'ids.*' => 'integer',
|
||||||
|
'category_id' => 'nullable|exists:categories,id',
|
||||||
|
'is_active' => 'nullable|boolean',
|
||||||
|
]);
|
||||||
|
|
||||||
|
$count = 0;
|
||||||
|
$isActive = $request->boolean('is_active', true);
|
||||||
|
$categoryId = $validated['category_id'] ?? null;
|
||||||
|
|
||||||
|
foreach ($validated['ids'] as $id) {
|
||||||
|
$details = $this->makerWorld->getDesignDetails($id);
|
||||||
|
if ($details) {
|
||||||
|
$this->makerWorld->importDesign(
|
||||||
|
$details,
|
||||||
|
$categoryId,
|
||||||
|
null,
|
||||||
|
null,
|
||||||
|
$isActive
|
||||||
|
);
|
||||||
|
$count++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return redirect()->back()->with('success', "{$count} modellen succesvol geïmporteerd naar je webshop!");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -54,12 +54,12 @@ class CartController extends Controller
|
|||||||
$unitPrice = round($unitPrice, 2);
|
$unitPrice = round($unitPrice, 2);
|
||||||
|
|
||||||
// Unieke sleutel in sessie op basis van product + configuratie
|
// Unieke sleutel in sessie op basis van product + configuratie
|
||||||
$cartKey = md5($product->id . '_' . $validated['material'] . '_' . $validated['color'] . '_' . $scale);
|
$cartKey = md5($product->id.'_'.$validated['material'].'_'.$validated['color'].'_'.$scale);
|
||||||
|
|
||||||
$cart = session()->get('cart', []);
|
$cart = session()->get('cart', []);
|
||||||
|
|
||||||
if (isset($cart[$cartKey])) {
|
if (isset($cart[$cartKey])) {
|
||||||
$cart[$cartKey]['quantity'] += (int)$validated['quantity'];
|
$cart[$cartKey]['quantity'] += (int) $validated['quantity'];
|
||||||
} else {
|
} else {
|
||||||
$cart[$cartKey] = [
|
$cart[$cartKey] = [
|
||||||
'id' => $product->id,
|
'id' => $product->id,
|
||||||
@@ -72,7 +72,7 @@ class CartController extends Controller
|
|||||||
'scale' => $scale,
|
'scale' => $scale,
|
||||||
'infill' => $validated['infill'] ?? 'Standaard (20%)',
|
'infill' => $validated['infill'] ?? 'Standaard (20%)',
|
||||||
'price' => $unitPrice,
|
'price' => $unitPrice,
|
||||||
'quantity' => (int)$validated['quantity'],
|
'quantity' => (int) $validated['quantity'],
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -99,7 +99,7 @@ class CartController extends Controller
|
|||||||
$cart = session()->get('cart', []);
|
$cart = session()->get('cart', []);
|
||||||
|
|
||||||
if (isset($cart[$validated['key']])) {
|
if (isset($cart[$validated['key']])) {
|
||||||
$cart[$validated['key']]['quantity'] = (int)$validated['quantity'];
|
$cart[$validated['key']]['quantity'] = (int) $validated['quantity'];
|
||||||
session()->put('cart', $cart);
|
session()->put('cart', $cart);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -56,7 +56,7 @@ class CheckoutController extends Controller
|
|||||||
$shipping = $subtotal > 50 ? 0.00 : 4.95;
|
$shipping = $subtotal > 50 ? 0.00 : 4.95;
|
||||||
$total = $subtotal + $shipping;
|
$total = $subtotal + $shipping;
|
||||||
|
|
||||||
$orderNumber = 'J3D-' . date('Y') . '-' . strtoupper(Str::random(6));
|
$orderNumber = 'J3D-'.date('Y').'-'.strtoupper(Str::random(6));
|
||||||
|
|
||||||
$order = Order::create([
|
$order = Order::create([
|
||||||
'order_number' => $orderNumber,
|
'order_number' => $orderNumber,
|
||||||
|
|||||||
@@ -42,6 +42,6 @@ class Order extends Model
|
|||||||
|
|
||||||
public function getFormattedTotalAttribute(): string
|
public function getFormattedTotalAttribute(): string
|
||||||
{
|
{
|
||||||
return '€ ' . number_format($this->total, 2, ',', '.');
|
return '€ '.number_format($this->total, 2, ',', '.');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ class Product extends Model
|
|||||||
use HasFactory;
|
use HasFactory;
|
||||||
|
|
||||||
protected $fillable = [
|
protected $fillable = [
|
||||||
|
'makerworld_id',
|
||||||
'category_id',
|
'category_id',
|
||||||
'name',
|
'name',
|
||||||
'slug',
|
'slug',
|
||||||
@@ -27,12 +28,16 @@ class Product extends Model
|
|||||||
'weight_grams',
|
'weight_grams',
|
||||||
'print_time_hours',
|
'print_time_hours',
|
||||||
'image_url',
|
'image_url',
|
||||||
|
'makerworld_url',
|
||||||
|
'makerworld_author',
|
||||||
|
'makerworld_license',
|
||||||
'gallery_images',
|
'gallery_images',
|
||||||
'available_materials',
|
'available_materials',
|
||||||
'available_colors',
|
'available_colors',
|
||||||
];
|
];
|
||||||
|
|
||||||
protected $casts = [
|
protected $casts = [
|
||||||
|
'makerworld_id' => 'integer',
|
||||||
'base_price' => 'float',
|
'base_price' => 'float',
|
||||||
'is_print_on_demand' => 'boolean',
|
'is_print_on_demand' => 'boolean',
|
||||||
'is_featured' => 'boolean',
|
'is_featured' => 'boolean',
|
||||||
@@ -55,6 +60,6 @@ class Product extends Model
|
|||||||
|
|
||||||
public function getFormattedPriceAttribute(): string
|
public function getFormattedPriceAttribute(): string
|
||||||
{
|
{
|
||||||
return '€ ' . number_format($this->base_price, 2, ',', '.');
|
return '€ '.number_format($this->base_price, 2, ',', '.');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,47 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Models;
|
||||||
|
|
||||||
|
use Illuminate\Database\Eloquent\Model;
|
||||||
|
|
||||||
|
class Setting extends Model
|
||||||
|
{
|
||||||
|
protected $primaryKey = 'key';
|
||||||
|
|
||||||
|
public $incrementing = false;
|
||||||
|
|
||||||
|
protected $keyType = 'string';
|
||||||
|
|
||||||
|
protected $fillable = [
|
||||||
|
'key',
|
||||||
|
'value',
|
||||||
|
];
|
||||||
|
|
||||||
|
public static function get(string $key, mixed $default = null): mixed
|
||||||
|
{
|
||||||
|
$setting = static::query()->find($key);
|
||||||
|
|
||||||
|
if (! $setting || $setting->value === null) {
|
||||||
|
return $default;
|
||||||
|
}
|
||||||
|
|
||||||
|
$decoded = json_decode($setting->value, true);
|
||||||
|
|
||||||
|
return (json_last_error() === JSON_ERROR_NONE) ? $decoded : $setting->value;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static function set(string $key, mixed $value): static
|
||||||
|
{
|
||||||
|
$encoded = is_array($value) || is_object($value) ? json_encode($value) : (string) $value;
|
||||||
|
|
||||||
|
return static::query()->updateOrCreate(
|
||||||
|
['key' => $key],
|
||||||
|
['value' => $encoded]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static function forget(string $key): bool
|
||||||
|
{
|
||||||
|
return (bool) static::query()->where('key', $key)->delete();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,525 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Services;
|
||||||
|
|
||||||
|
use App\Models\Product;
|
||||||
|
use App\Models\Setting;
|
||||||
|
use Illuminate\Http\Client\PendingRequest;
|
||||||
|
use Illuminate\Support\Facades\Http;
|
||||||
|
use Illuminate\Support\Facades\Log;
|
||||||
|
use Illuminate\Support\Str;
|
||||||
|
|
||||||
|
class MakerWorldService
|
||||||
|
{
|
||||||
|
protected string $baseUrl = 'https://api.bambulab.com';
|
||||||
|
|
||||||
|
protected string $userAgent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Build an HTTP client pre-configured with headers and optional bearer token.
|
||||||
|
*/
|
||||||
|
protected function client(): PendingRequest
|
||||||
|
{
|
||||||
|
$headers = [
|
||||||
|
'User-Agent' => $this->userAgent,
|
||||||
|
'Accept' => 'application/json, text/plain, */*',
|
||||||
|
];
|
||||||
|
|
||||||
|
$token = $this->getAccessToken();
|
||||||
|
if ($token) {
|
||||||
|
$headers['Authorization'] = 'Bearer '.$token;
|
||||||
|
}
|
||||||
|
|
||||||
|
return Http::withHeaders($headers)->timeout(15);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the stored access token.
|
||||||
|
*/
|
||||||
|
public function getAccessToken(): ?string
|
||||||
|
{
|
||||||
|
return Setting::get('makerworld_token');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Store the access token.
|
||||||
|
*/
|
||||||
|
public function setAccessToken(string $token): array
|
||||||
|
{
|
||||||
|
Setting::set('makerworld_token', trim($token));
|
||||||
|
$profile = $this->getUserProfile();
|
||||||
|
|
||||||
|
if ($profile) {
|
||||||
|
Setting::set('makerworld_user', $profile);
|
||||||
|
|
||||||
|
return [
|
||||||
|
'success' => true,
|
||||||
|
'user' => $profile,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
return [
|
||||||
|
'success' => true,
|
||||||
|
'user' => null,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check if currently authenticated with MakerWorld.
|
||||||
|
*/
|
||||||
|
public function isAuthenticated(): bool
|
||||||
|
{
|
||||||
|
return ! empty($this->getAccessToken());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Log out from MakerWorld by clearing saved credentials.
|
||||||
|
*/
|
||||||
|
public function logout(): void
|
||||||
|
{
|
||||||
|
Setting::forget('makerworld_token');
|
||||||
|
Setting::forget('makerworld_user');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Attempt to log in with MakerWorld account credentials (email and password).
|
||||||
|
*
|
||||||
|
* @return array{status: string, message?: string, token?: string, user?: array, account?: string}
|
||||||
|
*/
|
||||||
|
public function loginWithCredentials(string $account, string $password): array
|
||||||
|
{
|
||||||
|
try {
|
||||||
|
$response = Http::withHeaders([
|
||||||
|
'User-Agent' => $this->userAgent,
|
||||||
|
'Content-Type' => 'application/json',
|
||||||
|
])->post("{$this->baseUrl}/v1/user-service/user/login", [
|
||||||
|
'account' => $account,
|
||||||
|
'password' => $password,
|
||||||
|
'apiError' => '',
|
||||||
|
]);
|
||||||
|
|
||||||
|
$data = $response->json();
|
||||||
|
|
||||||
|
if (! empty($data['accessToken'])) {
|
||||||
|
$this->setAccessToken($data['accessToken']);
|
||||||
|
|
||||||
|
return [
|
||||||
|
'status' => 'success',
|
||||||
|
'token' => $data['accessToken'],
|
||||||
|
'message' => 'Succesvol ingelogd bij MakerWorld!',
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if 2FA code is needed
|
||||||
|
if (isset($data['loginType']) && $data['loginType'] === 'verifyCode') {
|
||||||
|
$this->sendEmailVerificationCode($account);
|
||||||
|
|
||||||
|
return [
|
||||||
|
'status' => '2fa_required',
|
||||||
|
'account' => $account,
|
||||||
|
'message' => 'Verificatiecode vereist. We hebben een 6-cijferige code naar je e-mail gestuurd.',
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
$errorMsg = $data['error'] ?? $data['message'] ?? 'Inloggen mislukt. Controleer je MakerWorld account en wachtwoord.';
|
||||||
|
|
||||||
|
return [
|
||||||
|
'status' => 'error',
|
||||||
|
'message' => $errorMsg,
|
||||||
|
];
|
||||||
|
} catch (\Throwable $e) {
|
||||||
|
Log::error('MakerWorld login error: '.$e->getMessage());
|
||||||
|
|
||||||
|
return [
|
||||||
|
'status' => 'error',
|
||||||
|
'message' => 'Verbinding met MakerWorld mislukt: '.$e->getMessage(),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Request an email verification code for Bambu / MakerWorld login.
|
||||||
|
*/
|
||||||
|
public function sendEmailVerificationCode(string $email): bool
|
||||||
|
{
|
||||||
|
try {
|
||||||
|
$response = Http::withHeaders([
|
||||||
|
'User-Agent' => $this->userAgent,
|
||||||
|
'Content-Type' => 'application/json',
|
||||||
|
])->post("{$this->baseUrl}/v1/user-service/user/sendemail/code", [
|
||||||
|
'email' => $email,
|
||||||
|
'type' => 'codeLogin',
|
||||||
|
]);
|
||||||
|
|
||||||
|
return $response->successful();
|
||||||
|
} catch (\Throwable $e) {
|
||||||
|
Log::error('MakerWorld send code error: '.$e->getMessage());
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Complete login with account and email verification code.
|
||||||
|
*/
|
||||||
|
public function verifyLoginCode(string $account, string $code): array
|
||||||
|
{
|
||||||
|
try {
|
||||||
|
$response = Http::withHeaders([
|
||||||
|
'User-Agent' => $this->userAgent,
|
||||||
|
'Content-Type' => 'application/json',
|
||||||
|
])->post("{$this->baseUrl}/v1/user-service/user/login", [
|
||||||
|
'account' => $account,
|
||||||
|
'code' => trim($code),
|
||||||
|
]);
|
||||||
|
|
||||||
|
$data = $response->json();
|
||||||
|
|
||||||
|
if (! empty($data['accessToken'])) {
|
||||||
|
$this->setAccessToken($data['accessToken']);
|
||||||
|
|
||||||
|
return [
|
||||||
|
'status' => 'success',
|
||||||
|
'token' => $data['accessToken'],
|
||||||
|
'message' => 'Verificatie geslaagd! Ingelogd bij MakerWorld.',
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
return [
|
||||||
|
'status' => 'error',
|
||||||
|
'message' => $data['error'] ?? $data['message'] ?? 'Ongeldige verificatiecode.',
|
||||||
|
];
|
||||||
|
} catch (\Throwable $e) {
|
||||||
|
Log::error('MakerWorld verify code error: '.$e->getMessage());
|
||||||
|
|
||||||
|
return [
|
||||||
|
'status' => 'error',
|
||||||
|
'message' => 'Verificatie mislukt: '.$e->getMessage(),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fetch user preference and profile.
|
||||||
|
*/
|
||||||
|
public function getUserProfile(): ?array
|
||||||
|
{
|
||||||
|
try {
|
||||||
|
$response = $this->client()->get("{$this->baseUrl}/v1/design-user-service/my/preference");
|
||||||
|
|
||||||
|
if ($response->successful()) {
|
||||||
|
return $response->json();
|
||||||
|
}
|
||||||
|
} catch (\Throwable $e) {
|
||||||
|
Log::warning('MakerWorld getUserProfile failed: '.$e->getMessage());
|
||||||
|
}
|
||||||
|
|
||||||
|
return Setting::get('makerworld_user');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fetch user's favorited models from MakerWorld.
|
||||||
|
*/
|
||||||
|
public function getFavorites(int $page = 1, int $limit = 24): array
|
||||||
|
{
|
||||||
|
if (! $this->isAuthenticated()) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
$response = $this->client()->get("{$this->baseUrl}/v1/design-service/my/design/favoriteslist", [
|
||||||
|
'page' => $page,
|
||||||
|
'limit' => $limit,
|
||||||
|
]);
|
||||||
|
|
||||||
|
if ($response->successful()) {
|
||||||
|
$data = $response->json();
|
||||||
|
|
||||||
|
return $data['hits'] ?? $data['designs'] ?? $data['list'] ?? (is_array($data) ? $data : []);
|
||||||
|
}
|
||||||
|
} catch (\Throwable $e) {
|
||||||
|
Log::error('MakerWorld getFavorites error: '.$e->getMessage());
|
||||||
|
}
|
||||||
|
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fetch user's published models from MakerWorld.
|
||||||
|
*/
|
||||||
|
public function getPublished(int $page = 1, int $limit = 24): array
|
||||||
|
{
|
||||||
|
if (! $this->isAuthenticated()) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
$response = $this->client()->get("{$this->baseUrl}/v1/design-service/my/design/published", [
|
||||||
|
'page' => $page,
|
||||||
|
'limit' => $limit,
|
||||||
|
]);
|
||||||
|
|
||||||
|
if ($response->successful()) {
|
||||||
|
$data = $response->json();
|
||||||
|
|
||||||
|
return $data['hits'] ?? $data['designs'] ?? $data['list'] ?? (is_array($data) ? $data : []);
|
||||||
|
}
|
||||||
|
} catch (\Throwable $e) {
|
||||||
|
Log::error('MakerWorld getPublished error: '.$e->getMessage());
|
||||||
|
}
|
||||||
|
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fetch popular showcase/contest models from MakerWorld.
|
||||||
|
*/
|
||||||
|
public function getCommunityShowcase(int $limit = 30): array
|
||||||
|
{
|
||||||
|
try {
|
||||||
|
$response = $this->client()->get("{$this->baseUrl}/v1/design-service/contest/list", [
|
||||||
|
'limit' => 3,
|
||||||
|
]);
|
||||||
|
|
||||||
|
if ($response->successful()) {
|
||||||
|
$data = $response->json();
|
||||||
|
$allDesigns = [];
|
||||||
|
|
||||||
|
if (! empty($data['hits']) && is_array($data['hits'])) {
|
||||||
|
foreach ($data['hits'] as $contest) {
|
||||||
|
if (! empty($contest['designs']) && is_array($contest['designs'])) {
|
||||||
|
foreach ($contest['designs'] as $design) {
|
||||||
|
$allDesigns[$design['id']] = $design;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return array_slice(array_values($allDesigns), 0, $limit);
|
||||||
|
}
|
||||||
|
} catch (\Throwable $e) {
|
||||||
|
Log::error('MakerWorld getCommunityShowcase error: '.$e->getMessage());
|
||||||
|
}
|
||||||
|
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get detailed design info by ID.
|
||||||
|
*/
|
||||||
|
public function getDesignDetails(int|string $designId): ?array
|
||||||
|
{
|
||||||
|
try {
|
||||||
|
$response = $this->client()->get("{$this->baseUrl}/v1/design-service/design/{$designId}");
|
||||||
|
|
||||||
|
if ($response->successful()) {
|
||||||
|
$data = $response->json();
|
||||||
|
if (! empty($data['id']) || ! empty($data['title'])) {
|
||||||
|
return $data;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (\Throwable $e) {
|
||||||
|
Log::error("MakerWorld getDesignDetails({$designId}) error: ".$e->getMessage());
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get batch of designs by IDs.
|
||||||
|
*/
|
||||||
|
public function getDesignsByIds(array $designIds): array
|
||||||
|
{
|
||||||
|
if (empty($designIds)) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
$ids = implode(',', array_filter(array_map('intval', $designIds)));
|
||||||
|
$response = $this->client()->get("{$this->baseUrl}/v1/design-service/design/ids", [
|
||||||
|
'designIds' => $ids,
|
||||||
|
]);
|
||||||
|
|
||||||
|
if ($response->successful()) {
|
||||||
|
$data = $response->json();
|
||||||
|
|
||||||
|
return $data['designs'] ?? [];
|
||||||
|
}
|
||||||
|
} catch (\Throwable $e) {
|
||||||
|
Log::error('MakerWorld getDesignsByIds error: '.$e->getMessage());
|
||||||
|
}
|
||||||
|
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Parse model ID from full MakerWorld URL or raw ID string.
|
||||||
|
* Examples:
|
||||||
|
* - https://makerworld.com/nl/models/55866#profileId-60000 -> 55866
|
||||||
|
* - https://makerworld.com/en/models/12345?keyword=test -> 12345
|
||||||
|
* - 55866 -> 55866
|
||||||
|
*/
|
||||||
|
public function parseModelId(string $input): ?int
|
||||||
|
{
|
||||||
|
$input = trim($input);
|
||||||
|
|
||||||
|
if (is_numeric($input)) {
|
||||||
|
return (int) $input;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (preg_match('/models\/(\d+)/i', $input, $matches)) {
|
||||||
|
return (int) $matches[1];
|
||||||
|
}
|
||||||
|
|
||||||
|
if (preg_match('/design\/(\d+)/i', $input, $matches)) {
|
||||||
|
return (int) $matches[1];
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Transform raw MakerWorld API design details into a clean format for product creation.
|
||||||
|
*/
|
||||||
|
public function formatDesignForImport(array $design): array
|
||||||
|
{
|
||||||
|
$designId = (int) ($design['id'] ?? 0);
|
||||||
|
$title = trim($design['title'] ?? 'MakerWorld 3D Model #'.$designId);
|
||||||
|
|
||||||
|
// Summary / Description cleanup
|
||||||
|
$rawSummary = $design['summary'] ?? $design['summaryTranslated'] ?? '';
|
||||||
|
$cleanDescription = $this->sanitizeHtml($rawSummary);
|
||||||
|
$shortDescription = Str::limit(strip_tags($rawSummary), 280);
|
||||||
|
|
||||||
|
// Cover & Gallery Images
|
||||||
|
$coverUrl = $design['coverUrl'] ?? $design['cover'] ?? null;
|
||||||
|
$gallery = [];
|
||||||
|
|
||||||
|
if (! empty($design['designExtension']['design_pictures']) && is_array($design['designExtension']['design_pictures'])) {
|
||||||
|
foreach ($design['designExtension']['design_pictures'] as $pic) {
|
||||||
|
if (! empty($pic['url']) && $pic['url'] !== $coverUrl) {
|
||||||
|
$gallery[] = $pic['url'];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (! empty($design['designExtension']['real_pictures']) && is_array($design['designExtension']['real_pictures'])) {
|
||||||
|
foreach ($design['designExtension']['real_pictures'] as $pic) {
|
||||||
|
if (! empty($pic['url']) && $pic['url'] !== $coverUrl && ! in_array($pic['url'], $gallery, true)) {
|
||||||
|
$gallery[] = $pic['url'];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Extract print profile stats (first/default instance)
|
||||||
|
$weightGrams = null;
|
||||||
|
$printTimeHours = null;
|
||||||
|
$materials = ['pla', 'petg'];
|
||||||
|
|
||||||
|
if (! empty($design['instances']) && is_array($design['instances'])) {
|
||||||
|
$profile = $design['instances'][0];
|
||||||
|
|
||||||
|
if (! empty($profile['weight'])) {
|
||||||
|
$weightGrams = (int) round($profile['weight']);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (! empty($profile['prediction'])) {
|
||||||
|
$seconds = (int) $profile['prediction'];
|
||||||
|
$printTimeHours = round($seconds / 3600, 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Calculate a smart suggested retail price
|
||||||
|
// Base starting price of 9.95, + ~0.08 per gram + 1.25 per print hour
|
||||||
|
$suggestedPrice = 14.95;
|
||||||
|
if ($weightGrams || $printTimeHours) {
|
||||||
|
$cost = 5.0;
|
||||||
|
if ($weightGrams) {
|
||||||
|
$cost += ($weightGrams * 0.07);
|
||||||
|
}
|
||||||
|
if ($printTimeHours) {
|
||||||
|
$cost += ($printTimeHours * 1.50);
|
||||||
|
}
|
||||||
|
$suggestedPrice = round(max(9.95, $cost * 1.6), 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Creator and MakerWorld URL
|
||||||
|
$authorName = $design['designCreator']['name'] ?? $design['designCreator']['handle'] ?? 'MakerWorld Creator';
|
||||||
|
$makerworldUrl = "https://makerworld.com/nl/models/{$designId}";
|
||||||
|
$license = $design['license'] ?? 'Standard MakerWorld License';
|
||||||
|
|
||||||
|
return [
|
||||||
|
'makerworld_id' => $designId,
|
||||||
|
'name' => $title,
|
||||||
|
'slug' => Str::slug($title),
|
||||||
|
'short_description' => $shortDescription,
|
||||||
|
'description' => $cleanDescription,
|
||||||
|
'base_price' => $suggestedPrice,
|
||||||
|
'sku' => 'MW-'.$designId,
|
||||||
|
'is_print_on_demand' => true,
|
||||||
|
'stock' => 15,
|
||||||
|
'is_featured' => false,
|
||||||
|
'is_active' => true,
|
||||||
|
'weight_grams' => $weightGrams,
|
||||||
|
'print_time_hours' => $printTimeHours,
|
||||||
|
'image_url' => $coverUrl,
|
||||||
|
'makerworld_url' => $makerworldUrl,
|
||||||
|
'makerworld_author' => $authorName,
|
||||||
|
'makerworld_license' => $license,
|
||||||
|
'gallery_images' => array_slice($gallery, 0, 8),
|
||||||
|
'available_materials' => $materials,
|
||||||
|
'available_colors' => ['Mat Zwart', 'Sneeuwwit', 'Leisteen Grijs', 'Koningsblauw'],
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Import or update a product from MakerWorld data.
|
||||||
|
*/
|
||||||
|
public function importDesign(
|
||||||
|
array $designData,
|
||||||
|
?int $categoryId = null,
|
||||||
|
?float $customPrice = null,
|
||||||
|
?string $customName = null,
|
||||||
|
bool $isActive = true
|
||||||
|
): Product {
|
||||||
|
$formatted = $this->formatDesignForImport($designData);
|
||||||
|
|
||||||
|
if ($customPrice !== null && $customPrice > 0) {
|
||||||
|
$formatted['base_price'] = $customPrice;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($customName !== null && trim($customName) !== '') {
|
||||||
|
$formatted['name'] = trim($customName);
|
||||||
|
$formatted['slug'] = Str::slug($formatted['name']);
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($categoryId !== null) {
|
||||||
|
$formatted['category_id'] = $categoryId;
|
||||||
|
}
|
||||||
|
|
||||||
|
$formatted['is_active'] = $isActive;
|
||||||
|
|
||||||
|
// Ensure slug is unique
|
||||||
|
$baseSlug = $formatted['slug'];
|
||||||
|
$count = 1;
|
||||||
|
while (Product::where('slug', $formatted['slug'])->where('makerworld_id', '!=', $formatted['makerworld_id'])->exists()) {
|
||||||
|
$formatted['slug'] = "{$baseSlug}-{$count}";
|
||||||
|
$count++;
|
||||||
|
}
|
||||||
|
|
||||||
|
return Product::updateOrCreate(
|
||||||
|
['makerworld_id' => $formatted['makerworld_id']],
|
||||||
|
$formatted
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Basic sanitization of MakerWorld HTML descriptions.
|
||||||
|
*/
|
||||||
|
protected function sanitizeHtml(string $html): string
|
||||||
|
{
|
||||||
|
$allowed = '<p><br><strong><b><em><i><u><ul><ol><li><h3><h4><h5><blockquote>';
|
||||||
|
|
||||||
|
return strip_tags($html, $allowed);
|
||||||
|
}
|
||||||
|
}
|
||||||
+17
@@ -0,0 +1,17 @@
|
|||||||
|
{
|
||||||
|
"agents": [
|
||||||
|
"antigravity"
|
||||||
|
],
|
||||||
|
"cloud": true,
|
||||||
|
"guidelines": true,
|
||||||
|
"mcp": true,
|
||||||
|
"nightwatch": false,
|
||||||
|
"sail": false,
|
||||||
|
"skills": [
|
||||||
|
"infer-conventions",
|
||||||
|
"deploying-to-cloud",
|
||||||
|
"laravel-best-practices",
|
||||||
|
"testing-best-practices",
|
||||||
|
"tailwindcss-development"
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -12,6 +12,7 @@
|
|||||||
},
|
},
|
||||||
"require-dev": {
|
"require-dev": {
|
||||||
"fakerphp/faker": "^1.23",
|
"fakerphp/faker": "^1.23",
|
||||||
|
"laravel/boost": "^2.10",
|
||||||
"laravel/pail": "^1.2.5",
|
"laravel/pail": "^1.2.5",
|
||||||
"laravel/pao": "^1.0.6",
|
"laravel/pao": "^1.0.6",
|
||||||
"laravel/pint": "^1.27",
|
"laravel/pint": "^1.27",
|
||||||
|
|||||||
Generated
+470
-224
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,36 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use Illuminate\Database\Migrations\Migration;
|
||||||
|
use Illuminate\Database\Schema\Blueprint;
|
||||||
|
use Illuminate\Support\Facades\Schema;
|
||||||
|
|
||||||
|
return new class extends Migration
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Run the migrations.
|
||||||
|
*/
|
||||||
|
public function up(): void
|
||||||
|
{
|
||||||
|
Schema::table('products', function (Blueprint $table) {
|
||||||
|
$table->unsignedBigInteger('makerworld_id')->nullable()->index()->after('id');
|
||||||
|
$table->string('makerworld_url')->nullable()->after('image_url');
|
||||||
|
$table->string('makerworld_author')->nullable()->after('makerworld_url');
|
||||||
|
$table->string('makerworld_license')->nullable()->after('makerworld_author');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reverse the migrations.
|
||||||
|
*/
|
||||||
|
public function down(): void
|
||||||
|
{
|
||||||
|
Schema::table('products', function (Blueprint $table) {
|
||||||
|
$table->dropColumn([
|
||||||
|
'makerworld_id',
|
||||||
|
'makerworld_url',
|
||||||
|
'makerworld_author',
|
||||||
|
'makerworld_license',
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use Illuminate\Database\Migrations\Migration;
|
||||||
|
use Illuminate\Database\Schema\Blueprint;
|
||||||
|
use Illuminate\Support\Facades\Schema;
|
||||||
|
|
||||||
|
return new class extends Migration
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Run the migrations.
|
||||||
|
*/
|
||||||
|
public function up(): void
|
||||||
|
{
|
||||||
|
Schema::create('settings', function (Blueprint $table) {
|
||||||
|
$table->string('key')->primary();
|
||||||
|
$table->longText('value')->nullable();
|
||||||
|
$table->timestamps();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reverse the migrations.
|
||||||
|
*/
|
||||||
|
public function down(): void
|
||||||
|
{
|
||||||
|
Schema::dropIfExists('settings');
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -117,7 +117,7 @@ class DatabaseSeeder extends Seeder
|
|||||||
'name' => 'Origami Geometrische Vaas',
|
'name' => 'Origami Geometrische Vaas',
|
||||||
'slug' => 'origami-geometrische-vaas',
|
'slug' => 'origami-geometrische-vaas',
|
||||||
'short_description' => 'Moderne vaas met scherpe facetten en minimalistische vouwlijnen. Een eyecatcher op elke tafel.',
|
'short_description' => 'Moderne vaas met scherpe facetten en minimalistische vouwlijnen. Een eyecatcher op elke tafel.',
|
||||||
'description' => "De Origami Vaas combineert traditionele vouwkunst met hypermoderne additieve fabricage. Geprint in spiralize vaasmodus of met versterkte wanden voor een 100% waterdichte afwerking bij keuze voor PETG. Ideaal voor droogbloemen of als sculptuur in je woonkamer.",
|
'description' => 'De Origami Vaas combineert traditionele vouwkunst met hypermoderne additieve fabricage. Geprint in spiralize vaasmodus of met versterkte wanden voor een 100% waterdichte afwerking bij keuze voor PETG. Ideaal voor droogbloemen of als sculptuur in je woonkamer.',
|
||||||
'base_price' => 18.95,
|
'base_price' => 18.95,
|
||||||
'sku' => 'J3D-VAS-001',
|
'sku' => 'J3D-VAS-001',
|
||||||
'is_featured' => true,
|
'is_featured' => true,
|
||||||
@@ -133,7 +133,7 @@ class DatabaseSeeder extends Seeder
|
|||||||
'name' => 'Ergonomische MagSafe Telefoon- & Watchhouder',
|
'name' => 'Ergonomische MagSafe Telefoon- & Watchhouder',
|
||||||
'slug' => 'ergonomische-magsafe-telefoonhouder',
|
'slug' => 'ergonomische-magsafe-telefoonhouder',
|
||||||
'short_description' => 'Strakke bureau-standaard met kabelgoot, geschikt voor iPhone MagSafe en smartwatch.',
|
'short_description' => 'Strakke bureau-standaard met kabelgoot, geschikt voor iPhone MagSafe en smartwatch.',
|
||||||
'description' => "Houd je bureau opgeruimd en je smartphone in de perfecte 65-graden kijkhoek voor videocalls of StandBy-modus. Voorzien van antislip voetpads en een slimme verborgen kabelgoot.",
|
'description' => 'Houd je bureau opgeruimd en je smartphone in de perfecte 65-graden kijkhoek voor videocalls of StandBy-modus. Voorzien van antislip voetpads en een slimme verborgen kabelgoot.',
|
||||||
'base_price' => 14.50,
|
'base_price' => 14.50,
|
||||||
'sku' => 'J3D-DSK-002',
|
'sku' => 'J3D-DSK-002',
|
||||||
'is_featured' => true,
|
'is_featured' => true,
|
||||||
@@ -149,7 +149,7 @@ class DatabaseSeeder extends Seeder
|
|||||||
'name' => 'Minimal Hoofdtelefoon Bureaustandaard',
|
'name' => 'Minimal Hoofdtelefoon Bureaustandaard',
|
||||||
'slug' => 'minimal-hoofdtelefoon-standaard',
|
'slug' => 'minimal-hoofdtelefoon-standaard',
|
||||||
'short_description' => 'Elegante boogstandaard om je headset veilig en vormvast op te bergen.',
|
'short_description' => 'Elegante boogstandaard om je headset veilig en vormvast op te bergen.',
|
||||||
'description' => "Geen rondslingerende hoofdtelefoons meer. Het brede steunvlak ontziet de hoofdband en voorkomt drukplekken in de kussens. Geprint met versterkte infill voor optimale stabiliteit.",
|
'description' => 'Geen rondslingerende hoofdtelefoons meer. Het brede steunvlak ontziet de hoofdband en voorkomt drukplekken in de kussens. Geprint met versterkte infill voor optimale stabiliteit.',
|
||||||
'base_price' => 22.50,
|
'base_price' => 22.50,
|
||||||
'sku' => 'J3D-DSK-003',
|
'sku' => 'J3D-DSK-003',
|
||||||
'is_featured' => true,
|
'is_featured' => true,
|
||||||
@@ -165,7 +165,7 @@ class DatabaseSeeder extends Seeder
|
|||||||
'name' => 'Articulated Flexibele Kristaldraak',
|
'name' => 'Articulated Flexibele Kristaldraak',
|
||||||
'slug' => 'articulated-flexibele-kristaldraak',
|
'slug' => 'articulated-flexibele-kristaldraak',
|
||||||
'short_description' => 'Print-in-place scharnierende draak met tientallen soepele schakels. Fascinerend fidget & decoratie-item.',
|
'short_description' => 'Print-in-place scharnierende draak met tientallen soepele schakels. Fascinerend fidget & decoratie-item.',
|
||||||
'description' => "In één stuk geprint zonder montage of schroeven! De schakels bewegen soepel en natuurlijk in je handen. Verkrijgbaar in zijdeglans en tweekleurige effecten.",
|
'description' => 'In één stuk geprint zonder montage of schroeven! De schakels bewegen soepel en natuurlijk in je handen. Verkrijgbaar in zijdeglans en tweekleurige effecten.',
|
||||||
'base_price' => 19.95,
|
'base_price' => 19.95,
|
||||||
'sku' => 'J3D-GAD-004',
|
'sku' => 'J3D-GAD-004',
|
||||||
'is_featured' => true,
|
'is_featured' => true,
|
||||||
@@ -181,7 +181,7 @@ class DatabaseSeeder extends Seeder
|
|||||||
'name' => 'Hexagon Modulaire Wandplankjes (Set van 3)',
|
'name' => 'Hexagon Modulaire Wandplankjes (Set van 3)',
|
||||||
'slug' => 'hexagon-modulaire-wandplankjes',
|
'slug' => 'hexagon-modulaire-wandplankjes',
|
||||||
'short_description' => 'Honingraat wanddisplay voor kleine plantjes, miniaturen of edelstenen. Inclusief onzichtbare wandmontage.',
|
'short_description' => 'Honingraat wanddisplay voor kleine plantjes, miniaturen of edelstenen. Inclusief onzichtbare wandmontage.',
|
||||||
'description' => "Creëer je eigen geometrische wandpatroon. Eenvoudig op te hangen met dubbelzijdige montagepads of kleine spijkers. Robuust ontworpen om kleine vetplantjes en beeldjes moeiteloos te dragen.",
|
'description' => 'Creëer je eigen geometrische wandpatroon. Eenvoudig op te hangen met dubbelzijdige montagepads of kleine spijkers. Robuust ontworpen om kleine vetplantjes en beeldjes moeiteloos te dragen.',
|
||||||
'base_price' => 27.50,
|
'base_price' => 27.50,
|
||||||
'sku' => 'J3D-HOM-005',
|
'sku' => 'J3D-HOM-005',
|
||||||
'is_featured' => false,
|
'is_featured' => false,
|
||||||
@@ -197,7 +197,7 @@ class DatabaseSeeder extends Seeder
|
|||||||
'name' => 'Heavy-Duty Boorkophouder & Magnetische Bit Tray',
|
'name' => 'Heavy-Duty Boorkophouder & Magnetische Bit Tray',
|
||||||
'slug' => 'heavy-duty-boorkophouder-bit-tray',
|
'slug' => 'heavy-duty-boorkophouder-bit-tray',
|
||||||
'short_description' => 'Georganiseerde opberger voor 1/4" hex bits en boorkoppen met krachtige Neodymium magneten.',
|
'short_description' => 'Georganiseerde opberger voor 1/4" hex bits en boorkoppen met krachtige Neodymium magneten.',
|
||||||
'description' => "Geprint in taai en chemicaliënbestendig PETG. Nooit meer losse schroefbits zoeken in je gereedschapskist. De magnetische bodem houdt al je metalen accessoires stevig op hun plek.",
|
'description' => 'Geprint in taai en chemicaliënbestendig PETG. Nooit meer losse schroefbits zoeken in je gereedschapskist. De magnetische bodem houdt al je metalen accessoires stevig op hun plek.',
|
||||||
'base_price' => 16.95,
|
'base_price' => 16.95,
|
||||||
'sku' => 'J3D-WRK-006',
|
'sku' => 'J3D-WRK-006',
|
||||||
'is_featured' => false,
|
'is_featured' => false,
|
||||||
|
|||||||
@@ -0,0 +1,735 @@
|
|||||||
|
@extends('layouts.app')
|
||||||
|
|
||||||
|
@section('title', 'MakerWorld Modellen Importeren | Jouwdriedee.nl Beheer')
|
||||||
|
|
||||||
|
@section('content')
|
||||||
|
<div class="bg-slate-900 text-white py-8 border-b border-slate-800" x-data="makerWorldApp()">
|
||||||
|
<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
|
||||||
|
|
||||||
|
<!-- Breadcrumb & Top Bar -->
|
||||||
|
<div class="flex flex-col md:flex-row md:items-center md:justify-between gap-4 pb-6 border-b border-slate-800">
|
||||||
|
<div>
|
||||||
|
<div class="flex items-center space-x-2 text-xs text-indigo-400 font-medium uppercase tracking-wider mb-1">
|
||||||
|
<span class="inline-block w-2 h-2 rounded-full bg-emerald-400 animate-pulse"></span>
|
||||||
|
<span>Backend Beheer</span>
|
||||||
|
<span>•</span>
|
||||||
|
<span>3D Model Synchronisatie</span>
|
||||||
|
</div>
|
||||||
|
<h1 class="text-2xl sm:text-3xl font-extrabold text-white flex items-center space-x-3">
|
||||||
|
<span class="p-2 bg-gradient-to-tr from-indigo-600 to-sky-500 rounded-xl text-white shadow-lg shadow-indigo-500/25">
|
||||||
|
<i data-lucide="layers" class="w-6 h-6"></i>
|
||||||
|
</span>
|
||||||
|
<span>MakerWorld Product Importer</span>
|
||||||
|
</h1>
|
||||||
|
<p class="mt-1 text-sm text-slate-400">
|
||||||
|
Haal eenvoudig 3D modellen binnen vanaf <a href="https://makerworld.com/nl/3d-models" target="_blank" class="text-indigo-400 hover:text-indigo-300 underline font-medium">makerworld.com</a> en publiceer ze direct in jouw webshop.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Account Connection Status Card -->
|
||||||
|
<div class="flex items-center space-x-3 bg-slate-800/80 backdrop-blur p-3 rounded-2xl border border-slate-700">
|
||||||
|
@if($isAuthenticated)
|
||||||
|
<div class="w-10 h-10 rounded-xl bg-emerald-500/20 border border-emerald-500/40 flex items-center justify-center text-emerald-400">
|
||||||
|
<i data-lucide="check-circle" class="w-5 h-5"></i>
|
||||||
|
</div>
|
||||||
|
<div class="text-left pr-2">
|
||||||
|
<div class="text-xs text-slate-400">MakerWorld Status</div>
|
||||||
|
<div class="text-sm font-semibold text-emerald-300 flex items-center space-x-1.5">
|
||||||
|
<span>Verbonden</span>
|
||||||
|
@if(!empty($userProfile['name']) || !empty($userProfile['account']))
|
||||||
|
<span class="text-xs text-slate-300 font-normal">({{ $userProfile['name'] ?? $userProfile['account'] }})</span>
|
||||||
|
@endif
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<form action="{{ route('admin.makerworld.disconnect') }}" method="POST">
|
||||||
|
@csrf
|
||||||
|
<button type="submit" class="px-3 py-1.5 text-xs font-medium text-rose-400 hover:text-rose-300 bg-rose-500/10 hover:bg-rose-500/20 rounded-lg border border-rose-500/30 transition-colors">
|
||||||
|
Ontkoppelen
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
@else
|
||||||
|
<div class="w-10 h-10 rounded-xl bg-amber-500/20 border border-amber-500/40 flex items-center justify-center text-amber-400">
|
||||||
|
<i data-lucide="shield-alert" class="w-5 h-5"></i>
|
||||||
|
</div>
|
||||||
|
<div class="text-left pr-2">
|
||||||
|
<div class="text-xs text-slate-400">MakerWorld Status</div>
|
||||||
|
<div class="text-sm font-semibold text-amber-300">Niet ingelogd</div>
|
||||||
|
</div>
|
||||||
|
<button type="button" @click="showLoginModal = true" class="px-3.5 py-1.5 text-xs font-semibold text-white bg-indigo-600 hover:bg-indigo-500 rounded-lg shadow-sm transition-colors flex items-center space-x-1">
|
||||||
|
<i data-lucide="log-in" class="w-3.5 h-3.5"></i>
|
||||||
|
<span>Inloggen</span>
|
||||||
|
</button>
|
||||||
|
@endif
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Notification Alerts -->
|
||||||
|
@if(session('success'))
|
||||||
|
<div class="mt-4 p-4 rounded-xl bg-emerald-950/60 border border-emerald-500/40 text-emerald-200 text-sm flex items-center space-x-3">
|
||||||
|
<i data-lucide="check-circle-2" class="w-5 h-5 text-emerald-400 shrink-0"></i>
|
||||||
|
<div class="font-medium">{{ session('success') }}</div>
|
||||||
|
</div>
|
||||||
|
@endif
|
||||||
|
|
||||||
|
@if(session('warning'))
|
||||||
|
<div class="mt-4 p-4 rounded-xl bg-amber-950/60 border border-amber-500/40 text-amber-200 text-sm flex items-center space-x-3">
|
||||||
|
<i data-lucide="alert-triangle" class="w-5 h-5 text-amber-400 shrink-0"></i>
|
||||||
|
<div class="font-medium">{{ session('warning') }}</div>
|
||||||
|
</div>
|
||||||
|
@endif
|
||||||
|
|
||||||
|
@if(session('error'))
|
||||||
|
<div class="mt-4 p-4 rounded-xl bg-rose-950/60 border border-rose-500/40 text-rose-200 text-sm flex items-center space-x-3">
|
||||||
|
<i data-lucide="x-circle" class="w-5 h-5 text-rose-400 shrink-0"></i>
|
||||||
|
<div class="font-medium">{{ session('error') }}</div>
|
||||||
|
</div>
|
||||||
|
@endif
|
||||||
|
|
||||||
|
<!-- Quick Import Search & Paste URL Bar -->
|
||||||
|
<div class="mt-8 bg-gradient-to-r from-slate-800 to-indigo-950/60 p-6 rounded-3xl border border-indigo-900/50 shadow-xl">
|
||||||
|
<div class="max-w-3xl">
|
||||||
|
<h2 class="text-lg font-bold text-white flex items-center space-x-2">
|
||||||
|
<i data-lucide="zap" class="w-5 h-5 text-amber-400"></i>
|
||||||
|
<span>Snel importeren via URL of Model-ID</span>
|
||||||
|
</h2>
|
||||||
|
<p class="text-xs text-slate-300 mt-1">
|
||||||
|
Kopieer een link van een willekeurig model op MakerWorld (bijv. <code>https://makerworld.com/nl/models/55866</code>) of vul het ID in.
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<form @submit.prevent="fetchQuickPreview()" class="mt-4 flex flex-col sm:flex-row gap-3">
|
||||||
|
<div class="relative flex-1">
|
||||||
|
<div class="absolute inset-y-0 left-0 pl-3.5 flex items-center pointer-events-none text-slate-400">
|
||||||
|
<i data-lucide="link" class="w-4 h-4"></i>
|
||||||
|
</div>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
x-model="quickInput"
|
||||||
|
placeholder="https://makerworld.com/nl/models/55866 of 55866..."
|
||||||
|
class="w-full pl-10 pr-4 py-3 bg-slate-900/90 border border-slate-700 rounded-xl text-white placeholder-slate-500 focus:outline-none focus:ring-2 focus:ring-indigo-500 text-sm font-mono"
|
||||||
|
required
|
||||||
|
>
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
:disabled="isLoadingQuick"
|
||||||
|
class="px-6 py-3 bg-indigo-600 hover:bg-indigo-500 disabled:opacity-50 text-white font-semibold rounded-xl text-sm flex items-center justify-center space-x-2 shadow-md transition-all shrink-0"
|
||||||
|
>
|
||||||
|
<template x-if="isLoadingQuick">
|
||||||
|
<div class="flex items-center space-x-2">
|
||||||
|
<svg class="animate-spin h-4 w-4 text-white" fill="none" viewBox="0 0 24 24">
|
||||||
|
<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
|
||||||
|
<path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8v8H4z"></path>
|
||||||
|
</svg>
|
||||||
|
<span>Ophalen...</span>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
<template x-if="!isLoadingQuick">
|
||||||
|
<div class="flex items-center space-x-2">
|
||||||
|
<i data-lucide="download-cloud" class="w-4 h-4"></i>
|
||||||
|
<span>Model Bekijken & Importeren</span>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Navigation Tabs -->
|
||||||
|
<div class="mt-8 border-b border-slate-800 flex items-center justify-between overflow-x-auto">
|
||||||
|
<nav class="flex space-x-3 sm:space-x-4">
|
||||||
|
@if($isAuthenticated)
|
||||||
|
<a href="{{ route('admin.makerworld.index', ['tab' => 'favorites']) }}"
|
||||||
|
class="pb-4 px-3 text-sm font-medium border-b-2 transition-colors flex items-center space-x-2 {{ $currentTab === 'favorites' ? 'border-indigo-500 text-indigo-400 font-bold' : 'border-transparent text-slate-400 hover:text-slate-200 hover:border-slate-700' }}">
|
||||||
|
<i data-lucide="heart" class="w-4 h-4 text-rose-400"></i>
|
||||||
|
<span>Mijn MakerWorld Favorieten</span>
|
||||||
|
</a>
|
||||||
|
<a href="{{ route('admin.makerworld.index', ['tab' => 'published']) }}"
|
||||||
|
class="pb-4 px-3 text-sm font-medium border-b-2 transition-colors flex items-center space-x-2 {{ $currentTab === 'published' ? 'border-indigo-500 text-indigo-400 font-bold' : 'border-transparent text-slate-400 hover:text-slate-200 hover:border-slate-700' }}">
|
||||||
|
<i data-lucide="folder" class="w-4 h-4 text-amber-400"></i>
|
||||||
|
<span>Mijn Gepubliceerde Modellen</span>
|
||||||
|
</a>
|
||||||
|
@endif
|
||||||
|
|
||||||
|
<a href="{{ route('admin.makerworld.index', ['tab' => 'community']) }}"
|
||||||
|
class="pb-4 px-3 text-sm font-medium border-b-2 transition-colors flex items-center space-x-2 {{ $currentTab === 'community' ? 'border-indigo-500 text-indigo-400 font-bold' : 'border-transparent text-slate-400 hover:text-slate-200 hover:border-slate-700' }}">
|
||||||
|
<i data-lucide="sparkles" class="w-4 h-4 text-sky-400"></i>
|
||||||
|
<span>Trending & Community Modellen</span>
|
||||||
|
</a>
|
||||||
|
|
||||||
|
<a href="{{ route('admin.makerworld.index', ['tab' => 'imported']) }}"
|
||||||
|
class="pb-4 px-3 text-sm font-medium border-b-2 transition-colors flex items-center space-x-2 {{ $currentTab === 'imported' ? 'border-indigo-500 text-indigo-400 font-bold' : 'border-transparent text-slate-400 hover:text-slate-200 hover:border-slate-700' }}">
|
||||||
|
<i data-lucide="shopping-bag" class="w-4 h-4 text-emerald-400"></i>
|
||||||
|
<span>In Webshop Geïmporteerd ({{ count($importedIds) }})</span>
|
||||||
|
</a>
|
||||||
|
</nav>
|
||||||
|
|
||||||
|
<a href="https://makerworld.com/nl/3d-models" target="_blank" class="hidden sm:flex items-center space-x-1.5 text-xs text-slate-400 hover:text-indigo-400 pb-3">
|
||||||
|
<span>Open MakerWorld</span>
|
||||||
|
<i data-lucide="external-link" class="w-3.5 h-3.5"></i>
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- TAB CONTENT: Models Grid (Favorites / Published / Community) -->
|
||||||
|
@if($currentTab !== 'imported')
|
||||||
|
<div class="mt-8">
|
||||||
|
|
||||||
|
@if(empty($models))
|
||||||
|
<div class="text-center py-16 bg-slate-800/40 rounded-3xl border border-slate-800">
|
||||||
|
<div class="w-16 h-16 rounded-2xl bg-slate-800 flex items-center justify-center text-slate-400 mx-auto mb-4">
|
||||||
|
<i data-lucide="box" class="w-8 h-8"></i>
|
||||||
|
</div>
|
||||||
|
<h3 class="text-lg font-bold text-white">Geen modellen gevonden in dit overzicht</h3>
|
||||||
|
<p class="text-sm text-slate-400 max-w-md mx-auto mt-1">
|
||||||
|
@if(!$isAuthenticated && in_array($currentTab, ['favorites', 'published']))
|
||||||
|
Log eerst in met je MakerWorld account om je opgeslagen favorieten of ontwerpen te bekijken.
|
||||||
|
@else
|
||||||
|
Probeer de trending modellen te bekijken of plak direct een URL in het zoekveld hierboven.
|
||||||
|
@endif
|
||||||
|
</p>
|
||||||
|
@if(!$isAuthenticated)
|
||||||
|
<button type="button" @click="showLoginModal = true" class="mt-5 px-5 py-2.5 bg-indigo-600 hover:bg-indigo-500 text-white rounded-xl text-sm font-semibold transition-colors">
|
||||||
|
Inloggen bij MakerWorld
|
||||||
|
</button>
|
||||||
|
@endif
|
||||||
|
</div>
|
||||||
|
@else
|
||||||
|
<!-- Batch selection controls header -->
|
||||||
|
<div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 mb-6">
|
||||||
|
<div class="text-sm text-slate-400">
|
||||||
|
<span>Toont <strong class="text-white">{{ count($models) }}</strong> modellen van MakerWorld. Vink modellen aan om ze in één klik te importeren.</span>
|
||||||
|
</div>
|
||||||
|
<div class="flex items-center space-x-3">
|
||||||
|
<button type="button" @click="toggleSelectAll()" class="text-xs text-indigo-400 hover:text-indigo-300 font-medium">
|
||||||
|
<span x-text="selectedIds.length === totalModels ? 'Deselecteer alles' : 'Selecteer alles op deze pagina'"></span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Products Grid -->
|
||||||
|
<div class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-6">
|
||||||
|
@foreach($models as $model)
|
||||||
|
@php
|
||||||
|
$mId = $model['id'] ?? 0;
|
||||||
|
$isAlreadyImported = in_array($mId, $importedIds);
|
||||||
|
$cover = $model['cover'] ?? $model['coverUrl'] ?? 'https://images.unsplash.com/photo-1581092160607-ee22621dd758?auto=format&fit=crop&w=600&q=80';
|
||||||
|
$title = $model['title'] ?? 'MakerWorld Model #' . $mId;
|
||||||
|
$author = $model['designCreator']['name'] ?? $model['designCreator']['handle'] ?? 'MakerWorld Maker';
|
||||||
|
@endphp
|
||||||
|
<div class="bg-slate-800/80 rounded-2xl border transition-all duration-200 overflow-hidden flex flex-col group {{ $isAlreadyImported ? 'border-emerald-500/40 shadow-sm' : 'border-slate-700/80 hover:border-indigo-500/50 hover:shadow-lg' }}">
|
||||||
|
|
||||||
|
<!-- Card Image -->
|
||||||
|
<div class="relative aspect-4/3 overflow-hidden bg-slate-900">
|
||||||
|
<img src="{{ $cover }}" alt="{{ $title }}" class="w-full h-full object-cover group-hover:scale-105 transition-transform duration-300" loading="lazy">
|
||||||
|
|
||||||
|
<!-- Selection Checkbox -->
|
||||||
|
<div class="absolute top-3 left-3 z-10">
|
||||||
|
<label class="flex items-center justify-center w-7 h-7 rounded-lg bg-slate-900/80 backdrop-blur border border-white/20 cursor-pointer shadow-md hover:scale-105 transition-transform">
|
||||||
|
<input type="checkbox" value="{{ $mId }}" x-model="selectedIds" class="w-4 h-4 text-indigo-600 rounded focus:ring-0">
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Status Badges -->
|
||||||
|
<div class="absolute top-3 right-3 flex flex-col gap-1.5 items-end">
|
||||||
|
@if($isAlreadyImported)
|
||||||
|
<span class="px-2 py-0.5 text-[11px] font-bold rounded-md bg-emerald-500 text-white shadow-md flex items-center space-x-1">
|
||||||
|
<i data-lucide="check" class="w-3 h-3 stroke-[3]"></i>
|
||||||
|
<span>In Webshop</span>
|
||||||
|
</span>
|
||||||
|
@endif
|
||||||
|
@if(!empty($model['printCount']))
|
||||||
|
<span class="px-2 py-0.5 text-[10px] font-medium rounded-md bg-slate-900/80 backdrop-blur text-slate-300 border border-white/10 flex items-center space-x-1">
|
||||||
|
<i data-lucide="printer" class="w-3 h-3 text-sky-400"></i>
|
||||||
|
<span>{{ number_format($model['printCount']) }} prints</span>
|
||||||
|
</span>
|
||||||
|
@endif
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<a href="https://makerworld.com/nl/models/{{ $mId }}" target="_blank" class="absolute bottom-2 right-2 p-1.5 rounded-lg bg-slate-900/80 backdrop-blur text-slate-300 hover:text-white border border-white/10 transition-colors" title="Bekijk op MakerWorld">
|
||||||
|
<i data-lucide="external-link" class="w-3.5 h-3.5"></i>
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Card Body -->
|
||||||
|
<div class="p-4 flex flex-col flex-1">
|
||||||
|
<div class="text-[11px] text-slate-400 mb-1 flex items-center justify-between">
|
||||||
|
<span class="truncate">Door {{ $author }}</span>
|
||||||
|
<span class="font-mono text-slate-500">#{{ $mId }}</span>
|
||||||
|
</div>
|
||||||
|
<h3 class="text-sm font-semibold text-white line-clamp-2 leading-snug mb-3 flex-1" title="{{ $title }}">
|
||||||
|
{{ $title }}
|
||||||
|
</h3>
|
||||||
|
|
||||||
|
<!-- Action Button -->
|
||||||
|
<div class="pt-3 border-t border-slate-700/60 flex items-center justify-between gap-2">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
@click="openImportModal({{ $mId }})"
|
||||||
|
class="w-full py-2 px-3 rounded-xl text-xs font-semibold flex items-center justify-center space-x-1.5 transition-colors {{ $isAlreadyImported ? 'bg-slate-700 hover:bg-slate-600 text-slate-200' : 'bg-indigo-600 hover:bg-indigo-500 text-white shadow-md shadow-indigo-600/20' }}"
|
||||||
|
>
|
||||||
|
<i data-lucide="{{ $isAlreadyImported ? 'refresh-cw' : 'plus-circle' }}" class="w-3.5 h-3.5"></i>
|
||||||
|
<span>{{ $isAlreadyImported ? 'Bewerken / Updaten' : 'Selecteer & Importeer' }}</span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
@endforeach
|
||||||
|
</div>
|
||||||
|
@endif
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- TAB CONTENT: Already Imported Products in Database -->
|
||||||
|
@else
|
||||||
|
<div class="mt-8">
|
||||||
|
<div class="flex items-center justify-between mb-6">
|
||||||
|
<div>
|
||||||
|
<h2 class="text-lg font-bold text-white">Geïmporteerde MakerWorld Producten in jouw Shop</h2>
|
||||||
|
<p class="text-xs text-slate-400">Deze producten zijn actief of opgeslagen in jouw webshop database.</p>
|
||||||
|
</div>
|
||||||
|
<a href="{{ route('catalog') }}" target="_blank" class="px-4 py-2 bg-slate-800 hover:bg-slate-700 text-white text-xs font-semibold rounded-xl border border-slate-700 flex items-center space-x-1.5 transition-colors">
|
||||||
|
<span>Bekijk publieke catalogus</span>
|
||||||
|
<i data-lucide="arrow-up-right" class="w-3.5 h-3.5"></i>
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
@if($importedProducts->isEmpty())
|
||||||
|
<div class="text-center py-16 bg-slate-800/40 rounded-3xl border border-slate-800">
|
||||||
|
<div class="w-16 h-16 rounded-2xl bg-slate-800 flex items-center justify-center text-slate-400 mx-auto mb-4">
|
||||||
|
<i data-lucide="package-open" class="w-8 h-8"></i>
|
||||||
|
</div>
|
||||||
|
<h3 class="text-lg font-bold text-white">Nog geen MakerWorld modellen geïmporteerd</h3>
|
||||||
|
<p class="text-sm text-slate-400 max-w-md mx-auto mt-1">
|
||||||
|
Selecteer hierboven modellen via de tabs of plak direct een MakerWorld link om je eerste product toe te voegen.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
@else
|
||||||
|
<div class="bg-slate-800/80 rounded-2xl border border-slate-700 overflow-hidden shadow-xl">
|
||||||
|
<div class="overflow-x-auto">
|
||||||
|
<table class="w-full text-left text-sm text-slate-300">
|
||||||
|
<thead class="bg-slate-900/60 text-xs text-slate-400 uppercase font-semibold border-b border-slate-700">
|
||||||
|
<tr>
|
||||||
|
<th class="py-3 px-4">Product</th>
|
||||||
|
<th class="py-3 px-4">MakerWorld Ref</th>
|
||||||
|
<th class="py-3 px-4">Categorie</th>
|
||||||
|
<th class="py-3 px-4">Verkoopprijs</th>
|
||||||
|
<th class="py-3 px-4">Print Specs</th>
|
||||||
|
<th class="py-3 px-4">Status</th>
|
||||||
|
<th class="py-3 px-4 text-right">Acties</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody class="divide-y divide-slate-700/60">
|
||||||
|
@foreach($importedProducts as $product)
|
||||||
|
<tr class="hover:bg-slate-750 transition-colors">
|
||||||
|
<td class="py-3 px-4 flex items-center space-x-3">
|
||||||
|
<img src="{{ $product->image_url }}" alt="{{ $product->name }}" class="w-12 h-12 rounded-lg object-cover bg-slate-900 shrink-0">
|
||||||
|
<div class="min-w-0">
|
||||||
|
<a href="{{ route('product.show', $product->slug) }}" target="_blank" class="font-semibold text-white hover:text-indigo-400 line-clamp-1">
|
||||||
|
{{ $product->name }}
|
||||||
|
</a>
|
||||||
|
<span class="text-xs text-slate-400">SKU: {{ $product->sku ?? 'MW-' . $product->makerworld_id }}</span>
|
||||||
|
</div>
|
||||||
|
</td>
|
||||||
|
<td class="py-3 px-4">
|
||||||
|
<a href="{{ $product->makerworld_url ?? 'https://makerworld.com/nl/models/' . $product->makerworld_id }}" target="_blank" class="text-xs text-indigo-400 hover:text-indigo-300 flex items-center space-x-1 font-mono">
|
||||||
|
<span>#{{ $product->makerworld_id }}</span>
|
||||||
|
<i data-lucide="external-link" class="w-3 h-3"></i>
|
||||||
|
</a>
|
||||||
|
<div class="text-[11px] text-slate-400">{{ $product->makerworld_author ?? 'MakerWorld' }}</div>
|
||||||
|
</td>
|
||||||
|
<td class="py-3 px-4">
|
||||||
|
<span class="px-2.5 py-1 rounded-md text-xs font-medium bg-slate-700 text-slate-300">
|
||||||
|
{{ $product->category->name ?? 'Ongecategoriseerd' }}
|
||||||
|
</span>
|
||||||
|
</td>
|
||||||
|
<td class="py-3 px-4 font-mono font-bold text-emerald-400">
|
||||||
|
{{ $product->formatted_price }}
|
||||||
|
</td>
|
||||||
|
<td class="py-3 px-4 text-xs text-slate-400">
|
||||||
|
@if($product->print_time_hours)
|
||||||
|
<div>⏱️ {{ $product->print_time_hours }} uur printtijd</div>
|
||||||
|
@endif
|
||||||
|
@if($product->weight_grams)
|
||||||
|
<div>⚖️ {{ $product->weight_grams }} gram filament</div>
|
||||||
|
@endif
|
||||||
|
</td>
|
||||||
|
<td class="py-3 px-4">
|
||||||
|
@if($product->is_active)
|
||||||
|
<span class="px-2 py-0.5 rounded-full text-[11px] font-semibold bg-emerald-500/20 text-emerald-400 border border-emerald-500/30">
|
||||||
|
Actief in shop
|
||||||
|
</span>
|
||||||
|
@else
|
||||||
|
<span class="px-2 py-0.5 rounded-full text-[11px] font-semibold bg-slate-700 text-slate-400">
|
||||||
|
Concept / Verborgen
|
||||||
|
</span>
|
||||||
|
@endif
|
||||||
|
</td>
|
||||||
|
<td class="py-3 px-4 text-right space-x-2">
|
||||||
|
<a href="{{ route('product.show', $product->slug) }}" target="_blank" class="p-1.5 text-slate-400 hover:text-white inline-block" title="Bekijk in webshop">
|
||||||
|
<i data-lucide="eye" class="w-4 h-4"></i>
|
||||||
|
</a>
|
||||||
|
<button type="button" @click="openImportModal({{ $product->makerworld_id }})" class="p-1.5 text-indigo-400 hover:text-indigo-300 inline-block" title="Bewerken / Opnieuw synchroniseren">
|
||||||
|
<i data-lucide="edit" class="w-4 h-4"></i>
|
||||||
|
</button>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
@endforeach
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
@if($importedProducts->hasPages())
|
||||||
|
<div class="p-4 border-t border-slate-700">
|
||||||
|
{{ $importedProducts->links() }}
|
||||||
|
</div>
|
||||||
|
@endif
|
||||||
|
</div>
|
||||||
|
@endif
|
||||||
|
</div>
|
||||||
|
@endif
|
||||||
|
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- FLOATING BATCH IMPORT BAR (When items are checked) -->
|
||||||
|
<div
|
||||||
|
x-show="selectedIds.length > 0"
|
||||||
|
x-transition:enter="transition ease-out duration-300"
|
||||||
|
x-transition:enter-start="opacity-0 translate-y-8"
|
||||||
|
x-transition:enter-end="opacity-100 translate-y-0"
|
||||||
|
x-transition:leave="transition ease-in duration-200"
|
||||||
|
x-transition:leave-start="opacity-100 translate-y-0"
|
||||||
|
x-transition:leave-end="opacity-0 translate-y-8"
|
||||||
|
class="fixed bottom-6 inset-x-0 z-40 max-w-4xl mx-auto px-4 pointer-events-none"
|
||||||
|
>
|
||||||
|
<div class="bg-indigo-950/95 backdrop-blur-md border border-indigo-500/50 shadow-2xl rounded-2xl p-4 text-white flex flex-col sm:flex-row items-center justify-between gap-4 pointer-events-auto">
|
||||||
|
<div class="flex items-center space-x-3">
|
||||||
|
<div class="w-9 h-9 rounded-xl bg-indigo-500/20 border border-indigo-400/40 flex items-center justify-center font-bold text-indigo-300">
|
||||||
|
<span x-text="selectedIds.length"></span>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<div class="text-sm font-bold text-white"><span x-text="selectedIds.length"></span> modellen geselecteerd</div>
|
||||||
|
<div class="text-xs text-indigo-300">Klaar om direct te publiceren in je webshop</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<form action="{{ route('admin.makerworld.batch-import') }}" method="POST" class="flex items-center space-x-3 w-full sm:w-auto">
|
||||||
|
@csrf
|
||||||
|
<template x-for="id in selectedIds" :key="id">
|
||||||
|
<input type="hidden" name="ids[]" :value="id">
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<select name="category_id" class="bg-slate-900 border border-indigo-700 rounded-xl px-3 py-2 text-xs text-white focus:ring-2 focus:ring-indigo-400">
|
||||||
|
<option value="">Kies standaard categorie...</option>
|
||||||
|
@foreach($categories as $category)
|
||||||
|
<option value="{{ $category->id }}">{{ $category->name }}</option>
|
||||||
|
@endforeach
|
||||||
|
</select>
|
||||||
|
|
||||||
|
<button type="submit" class="px-5 py-2.5 bg-gradient-to-r from-emerald-500 to-teal-500 hover:from-emerald-600 hover:to-teal-600 font-bold text-xs text-white rounded-xl shadow-lg transition-transform hover:scale-105 shrink-0 flex items-center space-x-1.5">
|
||||||
|
<i data-lucide="download" class="w-4 h-4"></i>
|
||||||
|
<span>Alles Nu Importeren</span>
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<button type="button" @click="selectedIds = []" class="p-2 text-indigo-300 hover:text-white" title="Annuleren">
|
||||||
|
<i data-lucide="x" class="w-4 h-4"></i>
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- MODAL: LOGIN / AUTHENTICATIE MET MAKERWORLD -->
|
||||||
|
<div
|
||||||
|
x-show="showLoginModal"
|
||||||
|
x-cloak
|
||||||
|
class="fixed inset-0 z-50 overflow-y-auto bg-slate-950/80 backdrop-blur-sm flex items-center justify-center p-4"
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
@click.away="showLoginModal = false"
|
||||||
|
class="bg-slate-900 border border-slate-800 rounded-3xl max-w-lg w-full p-6 sm:p-8 shadow-2xl relative text-slate-100"
|
||||||
|
>
|
||||||
|
<button @click="showLoginModal = false" class="absolute top-5 right-5 text-slate-400 hover:text-white">
|
||||||
|
<i data-lucide="x" class="w-5 h-5"></i>
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<div class="flex items-center space-x-3 mb-4">
|
||||||
|
<div class="w-12 h-12 rounded-2xl bg-indigo-600/20 border border-indigo-500/30 flex items-center justify-center text-indigo-400">
|
||||||
|
<i data-lucide="key-round" class="w-6 h-6"></i>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<h3 class="text-xl font-extrabold text-white">Inloggen bij MakerWorld</h3>
|
||||||
|
<p class="text-xs text-slate-400">Koppel jouw MakerWorld / Bambu Lab account</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Login Method Tabs -->
|
||||||
|
<div class="flex space-x-2 border-b border-slate-800 pb-3 mb-6">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
@click="loginTab = 'credentials'"
|
||||||
|
:class="loginTab === 'credentials' ? 'text-indigo-400 border-b-2 border-indigo-500 font-bold' : 'text-slate-400 hover:text-white'"
|
||||||
|
class="pb-2 text-xs font-semibold px-2 transition-colors"
|
||||||
|
>
|
||||||
|
Account (E-mail & Wachtwoord)
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
@click="loginTab = 'token'"
|
||||||
|
:class="loginTab === 'token' ? 'text-indigo-400 border-b-2 border-indigo-500 font-bold' : 'text-slate-400 hover:text-white'"
|
||||||
|
class="pb-2 text-xs font-semibold px-2 transition-colors"
|
||||||
|
>
|
||||||
|
Direct Token / Sessie Plakken
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- METHOD 1: Credentials / 2FA -->
|
||||||
|
<div x-show="loginTab === 'credentials'">
|
||||||
|
@if(session('makerworld_2fa_account'))
|
||||||
|
<!-- 2FA Verification Code Form -->
|
||||||
|
<form action="{{ route('admin.makerworld.verify-code') }}" method="POST" class="space-y-4">
|
||||||
|
@csrf
|
||||||
|
<input type="hidden" name="account" value="{{ session('makerworld_2fa_account') }}">
|
||||||
|
<div class="p-4 rounded-xl bg-amber-500/10 border border-amber-500/30 text-amber-200 text-xs">
|
||||||
|
Voer de 6-cijferige verificatiecode in die Bambu Lab zojuist naar <strong>{{ session('makerworld_2fa_account') }}</strong> heeft gemaild.
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label class="block text-xs font-semibold text-slate-300 mb-1.5">6-cijferige Beveiligingscode</label>
|
||||||
|
<input type="text" name="code" maxlength="6" placeholder="123456" class="w-full text-center tracking-widest font-mono text-xl py-3 bg-slate-800 border border-slate-700 rounded-xl text-white focus:ring-2 focus:ring-indigo-500" required autofocus>
|
||||||
|
</div>
|
||||||
|
<button type="submit" class="w-full py-3 bg-emerald-600 hover:bg-emerald-500 text-white font-bold rounded-xl text-sm shadow-lg transition-colors">
|
||||||
|
Verifiëren & Verbinden
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
@else
|
||||||
|
<!-- Account & Password Form -->
|
||||||
|
<form action="{{ route('admin.makerworld.login') }}" method="POST" class="space-y-4">
|
||||||
|
@csrf
|
||||||
|
<div>
|
||||||
|
<label class="block text-xs font-semibold text-slate-300 mb-1.5">MakerWorld / Bambu Lab E-mailadres</label>
|
||||||
|
<input type="email" name="account" placeholder="jouw@email.nl" class="w-full px-4 py-2.5 bg-slate-800 border border-slate-700 rounded-xl text-white placeholder-slate-500 text-sm focus:ring-2 focus:ring-indigo-500" required>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label class="block text-xs font-semibold text-slate-300 mb-1.5">Wachtwoord</label>
|
||||||
|
<input type="password" name="password" placeholder="••••••••" class="w-full px-4 py-2.5 bg-slate-800 border border-slate-700 rounded-xl text-white placeholder-slate-500 text-sm focus:ring-2 focus:ring-indigo-500" required>
|
||||||
|
</div>
|
||||||
|
<p class="text-[11px] text-slate-400 leading-relaxed">
|
||||||
|
💡 Heeft je Bambu Lab account 2-stapsverificatie? Dan ontvang je automatisch een code per e-mail die je in de volgende stap invult.
|
||||||
|
</p>
|
||||||
|
<button type="submit" class="w-full py-3 bg-indigo-600 hover:bg-indigo-500 text-white font-bold rounded-xl text-sm shadow-lg shadow-indigo-600/30 transition-colors">
|
||||||
|
Inloggen bij MakerWorld
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
@endif
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- METHOD 2: Direct Token / Cookie -->
|
||||||
|
<div x-show="loginTab === 'token'">
|
||||||
|
<form action="{{ route('admin.makerworld.token') }}" method="POST" class="space-y-4">
|
||||||
|
@csrf
|
||||||
|
<div>
|
||||||
|
<label class="block text-xs font-semibold text-slate-300 mb-1.5">Bambu Cloud / MakerWorld Access Token</label>
|
||||||
|
<textarea name="token" rows="4" placeholder="Plak hier je Bearer accessToken (bijv. vanuit F12 browser inspect of Bambu Studio)..." class="w-full p-3 font-mono text-xs bg-slate-800 border border-slate-700 rounded-xl text-white placeholder-slate-500 focus:ring-2 focus:ring-indigo-500" required></textarea>
|
||||||
|
</div>
|
||||||
|
<div class="text-[11px] text-slate-400 bg-slate-800/60 p-3 rounded-xl border border-slate-800">
|
||||||
|
<strong>Hoe vind je dit token?</strong><br>
|
||||||
|
Als je al bent ingelogd op <a href="https://makerworld.com" target="_blank" class="text-indigo-400 underline">makerworld.com</a> in je browser, druk op <code>F12</code> → tabblad <em>Toepassing/Application</em> → <em>Cookies</em> → kopieer de waarde van het <code>token</code> cookie.
|
||||||
|
</div>
|
||||||
|
<button type="submit" class="w-full py-3 bg-indigo-600 hover:bg-indigo-500 text-white font-bold rounded-xl text-sm shadow-lg shadow-indigo-600/30 transition-colors">
|
||||||
|
Token Opslaan & Verbinden
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- MODAL: MODEL BEKIJKEN & IMPORTEREN -->
|
||||||
|
<div
|
||||||
|
x-show="showImportModal"
|
||||||
|
x-cloak
|
||||||
|
class="fixed inset-0 z-50 overflow-y-auto bg-slate-950/85 backdrop-blur-sm flex items-center justify-center p-4"
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
@click.away="showImportModal = false"
|
||||||
|
class="bg-slate-900 border border-slate-800 rounded-3xl max-w-2xl w-full p-6 sm:p-8 shadow-2xl relative text-slate-100 max-h-[90vh] overflow-y-auto"
|
||||||
|
>
|
||||||
|
<button @click="showImportModal = false" class="absolute top-5 right-5 text-slate-400 hover:text-white">
|
||||||
|
<i data-lucide="x" class="w-5 h-5"></i>
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<!-- Loading State -->
|
||||||
|
<div x-show="isLoadingModal" class="py-16 text-center">
|
||||||
|
<svg class="animate-spin h-8 w-8 text-indigo-500 mx-auto mb-3" fill="none" viewBox="0 0 24 24">
|
||||||
|
<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
|
||||||
|
<path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8v8H4z"></path>
|
||||||
|
</svg>
|
||||||
|
<div class="text-sm text-slate-300 font-semibold">Model gegevens ophalen van MakerWorld...</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Model Details Form -->
|
||||||
|
<div x-show="!isLoadingModal && activeModel">
|
||||||
|
<form action="{{ route('admin.makerworld.import') }}" method="POST">
|
||||||
|
@csrf
|
||||||
|
<input type="hidden" name="makerworld_id" :value="activeModel?.makerworld_id">
|
||||||
|
|
||||||
|
<!-- Header with Image & Title -->
|
||||||
|
<div class="flex flex-col sm:flex-row gap-5 pb-6 border-b border-slate-800">
|
||||||
|
<img :src="activeModel?.image_url" class="w-full sm:w-36 h-36 rounded-2xl object-cover bg-slate-950 shadow-md shrink-0">
|
||||||
|
<div class="flex-1">
|
||||||
|
<div class="flex items-center space-x-2 text-xs text-indigo-400 font-semibold mb-1">
|
||||||
|
<span x-text="'MakerWorld #' + activeModel?.makerworld_id"></span>
|
||||||
|
<span>•</span>
|
||||||
|
<span x-text="'Door ' + activeModel?.makerworld_author"></span>
|
||||||
|
</div>
|
||||||
|
<h3 class="text-lg font-bold text-white leading-tight" x-text="activeModel?.name"></h3>
|
||||||
|
<p class="text-xs text-slate-400 line-clamp-3 mt-2" x-text="activeModel?.short_description"></p>
|
||||||
|
|
||||||
|
<!-- Specifications Pill -->
|
||||||
|
<div class="flex flex-wrap gap-2 mt-3 text-[11px] text-slate-300">
|
||||||
|
<span class="px-2.5 py-1 rounded-lg bg-slate-800 border border-slate-700 flex items-center space-x-1">
|
||||||
|
<i data-lucide="clock" class="w-3 h-3 text-sky-400"></i>
|
||||||
|
<span x-text="activeModel?.print_time_hours ? activeModel?.print_time_hours + ' uur' : 'Onbekend'"></span>
|
||||||
|
</span>
|
||||||
|
<span class="px-2.5 py-1 rounded-lg bg-slate-800 border border-slate-700 flex items-center space-x-1">
|
||||||
|
<i data-lucide="scale" class="w-3 h-3 text-amber-400"></i>
|
||||||
|
<span x-text="activeModel?.weight_grams ? activeModel?.weight_grams + ' gram' : 'Onbekend'"></span>
|
||||||
|
</span>
|
||||||
|
<span class="px-2.5 py-1 rounded-lg bg-slate-800 border border-slate-700 flex items-center space-x-1">
|
||||||
|
<i data-lucide="shield" class="w-3 h-3 text-emerald-400"></i>
|
||||||
|
<span x-text="activeModel?.makerworld_license ?? 'Standaard Licentie'"></span>
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Custom Form Fields -->
|
||||||
|
<div class="space-y-4 pt-6">
|
||||||
|
<div>
|
||||||
|
<label class="block text-xs font-semibold text-slate-300 mb-1">Producttitel in jouw Webshop</label>
|
||||||
|
<input type="text" name="custom_name" x-model="activeModel.name" class="w-full px-4 py-2.5 bg-slate-800 border border-slate-700 rounded-xl text-white text-sm focus:ring-2 focus:ring-indigo-500">
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
|
||||||
|
<div>
|
||||||
|
<label class="block text-xs font-semibold text-slate-300 mb-1">Koppel aan Categorie</label>
|
||||||
|
<select name="category_id" class="w-full px-4 py-2.5 bg-slate-800 border border-slate-700 rounded-xl text-white text-sm focus:ring-2 focus:ring-indigo-500">
|
||||||
|
<option value="">Geen categorie (standaard)</option>
|
||||||
|
@foreach($categories as $category)
|
||||||
|
<option value="{{ $category->id }}">{{ $category->name }}</option>
|
||||||
|
@endforeach
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label class="block text-xs font-semibold text-slate-300 mb-1">
|
||||||
|
<span>Verkoopprijs (€)</span>
|
||||||
|
<span class="text-slate-400 font-normal ml-1">(incl. marge & printkosten)</span>
|
||||||
|
</label>
|
||||||
|
<input type="number" step="0.01" min="1" name="custom_price" x-model="activeModel.base_price" class="w-full px-4 py-2.5 bg-slate-800 border border-slate-700 rounded-xl text-white text-sm font-mono focus:ring-2 focus:ring-indigo-500" required>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Active Switch -->
|
||||||
|
<div class="flex items-center justify-between p-4 bg-slate-800/60 rounded-2xl border border-slate-700">
|
||||||
|
<div>
|
||||||
|
<div class="text-sm font-semibold text-white">Direct actief in de webshop</div>
|
||||||
|
<div class="text-xs text-slate-400">Bezoekers kunnen dit product direct bekijken en bestellen</div>
|
||||||
|
</div>
|
||||||
|
<label class="relative inline-flex items-center cursor-pointer">
|
||||||
|
<input type="checkbox" name="is_active" value="1" checked class="sr-only peer">
|
||||||
|
<div class="w-11 h-6 bg-slate-700 peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-slate-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-emerald-500"></div>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Footer Action -->
|
||||||
|
<div class="mt-8 flex items-center justify-end space-x-3 pt-6 border-t border-slate-800">
|
||||||
|
<button type="button" @click="showImportModal = false" class="px-5 py-2.5 rounded-xl text-xs font-semibold text-slate-400 hover:text-white transition-colors">
|
||||||
|
Annuleren
|
||||||
|
</button>
|
||||||
|
<button type="submit" class="px-6 py-2.5 bg-gradient-to-r from-indigo-600 to-sky-500 hover:from-indigo-500 hover:to-sky-400 text-white font-bold text-sm rounded-xl shadow-lg shadow-indigo-500/25 transition-transform hover:scale-105 flex items-center space-x-2">
|
||||||
|
<i data-lucide="check" class="w-4 h-4"></i>
|
||||||
|
<span>Toevoegen aan Webshop</span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
function makerWorldApp() {
|
||||||
|
return {
|
||||||
|
showLoginModal: {{ session('makerworld_2fa_account') ? 'true' : 'false' }},
|
||||||
|
loginTab: 'credentials',
|
||||||
|
showImportModal: false,
|
||||||
|
isLoadingModal: false,
|
||||||
|
isLoadingQuick: false,
|
||||||
|
quickInput: '',
|
||||||
|
activeModel: null,
|
||||||
|
selectedIds: [],
|
||||||
|
totalModels: {{ count($models) }},
|
||||||
|
|
||||||
|
toggleSelectAll() {
|
||||||
|
if (this.selectedIds.length === this.totalModels) {
|
||||||
|
this.selectedIds = [];
|
||||||
|
} else {
|
||||||
|
this.selectedIds = @json(array_column($models, 'id'));
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
async openImportModal(id) {
|
||||||
|
this.showImportModal = true;
|
||||||
|
this.isLoadingModal = true;
|
||||||
|
this.activeModel = null;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await fetch(`{{ route('admin.makerworld.preview') }}?query=${id}`);
|
||||||
|
const data = await response.json();
|
||||||
|
|
||||||
|
if (response.ok && data.model) {
|
||||||
|
this.activeModel = data.model;
|
||||||
|
} else {
|
||||||
|
alert(data.error || 'Kon model niet ophalen');
|
||||||
|
this.showImportModal = false;
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
alert('Fout bij ophalen van model: ' + err.message);
|
||||||
|
this.showImportModal = false;
|
||||||
|
} finally {
|
||||||
|
this.isLoadingModal = false;
|
||||||
|
this.$nextTick(() => {
|
||||||
|
if (window.lucide) {
|
||||||
|
window.lucide.createIcons();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
async fetchQuickPreview() {
|
||||||
|
if (!this.quickInput.trim()) return;
|
||||||
|
|
||||||
|
this.isLoadingQuick = true;
|
||||||
|
try {
|
||||||
|
const response = await fetch(`{{ route('admin.makerworld.preview') }}?query=${encodeURIComponent(this.quickInput)}`);
|
||||||
|
const data = await response.json();
|
||||||
|
|
||||||
|
if (response.ok && data.model) {
|
||||||
|
this.activeModel = data.model;
|
||||||
|
this.showImportModal = true;
|
||||||
|
} else {
|
||||||
|
alert(data.error || 'Kon model niet vinden op MakerWorld.');
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
alert('Fout bij ophalen van model: ' + err.message);
|
||||||
|
} finally {
|
||||||
|
this.isLoadingQuick = false;
|
||||||
|
this.$nextTick(() => {
|
||||||
|
if (window.lucide) {
|
||||||
|
window.lucide.createIcons();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
@endsection
|
||||||
|
|
||||||
@@ -70,6 +70,10 @@
|
|||||||
<i data-lucide="printer" class="w-4 h-4 text-indigo-500"></i>
|
<i data-lucide="printer" class="w-4 h-4 text-indigo-500"></i>
|
||||||
<span>Eigen STL Printen</span>
|
<span>Eigen STL Printen</span>
|
||||||
</a>
|
</a>
|
||||||
|
<a href="{{ route('admin.makerworld.index') }}" class="px-3.5 py-2 rounded-xl transition flex items-center space-x-1.5 {{ request()->routeIs('admin.makerworld*') ? 'bg-indigo-600 text-white font-bold shadow-sm' : 'text-slate-600 hover:text-slate-900 hover:bg-slate-100/70' }}">
|
||||||
|
<i data-lucide="layers" class="w-4 h-4 {{ request()->routeIs('admin.makerworld*') ? 'text-white' : 'text-indigo-600' }}"></i>
|
||||||
|
<span>MakerWorld Importer</span>
|
||||||
|
</a>
|
||||||
</nav>
|
</nav>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -130,6 +134,10 @@
|
|||||||
<i data-lucide="printer" class="w-4 h-4"></i>
|
<i data-lucide="printer" class="w-4 h-4"></i>
|
||||||
<span>Eigen 3D Model Printen (Upload)</span>
|
<span>Eigen 3D Model Printen (Upload)</span>
|
||||||
</a>
|
</a>
|
||||||
|
<a href="{{ route('admin.makerworld.index') }}" class="px-3.5 py-2.5 rounded-xl text-sm font-semibold text-slate-700 hover:bg-slate-50 flex items-center space-x-2">
|
||||||
|
<i data-lucide="layers" class="w-4 h-4 text-indigo-600"></i>
|
||||||
|
<span>MakerWorld Importer (Beheer)</span>
|
||||||
|
</a>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</header>
|
</header>
|
||||||
|
|||||||
@@ -116,12 +116,26 @@
|
|||||||
<!-- Productomschrijving -->
|
<!-- Productomschrijving -->
|
||||||
<div class="p-6 rounded-3xl bg-white border border-slate-200 shadow-2xs space-y-3">
|
<div class="p-6 rounded-3xl bg-white border border-slate-200 shadow-2xs space-y-3">
|
||||||
<h3 class="text-sm font-bold text-slate-900">Over dit product</h3>
|
<h3 class="text-sm font-bold text-slate-900">Over dit product</h3>
|
||||||
<p class="text-xs text-slate-600 leading-relaxed whitespace-pre-line">
|
<div class="text-xs text-slate-600 leading-relaxed space-y-2">
|
||||||
{{ $product->description }}
|
{!! nl2br($product->description) !!}
|
||||||
</p>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
@if($product->makerworld_id)
|
||||||
|
<!-- MakerWorld Model Attributie -->
|
||||||
|
<div class="p-4 rounded-2xl bg-indigo-50/50 border border-indigo-100/80 text-xs text-slate-600 flex items-center justify-between">
|
||||||
|
<div class="flex items-center space-x-2">
|
||||||
|
<span class="px-2 py-0.5 rounded bg-indigo-100 text-indigo-700 font-bold text-[10px]">MakerWorld Model</span>
|
||||||
|
<span>Ontworpen door <strong class="text-slate-800">{{ $product->makerworld_author ?? 'MakerWorld Creator' }}</strong></span>
|
||||||
|
</div>
|
||||||
|
<a href="{{ $product->makerworld_url ?? 'https://makerworld.com/nl/models/' . $product->makerworld_id }}" target="_blank" class="text-indigo-600 hover:text-indigo-800 font-semibold inline-flex items-center space-x-1">
|
||||||
|
<span>Bronbekijken</span>
|
||||||
|
<i data-lucide="external-link" class="w-3 h-3"></i>
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
@endif
|
||||||
|
</div>
|
||||||
|
|
||||||
<!-- Rechterkant: Interactive 3D Configurator & Bestelmodule -->
|
<!-- Rechterkant: Interactive 3D Configurator & Bestelmodule -->
|
||||||
<div class="lg:col-span-6 space-y-6">
|
<div class="lg:col-span-6 space-y-6">
|
||||||
<div class="p-7 rounded-3xl bg-white border border-slate-200 shadow-md space-y-6">
|
<div class="p-7 rounded-3xl bg-white border border-slate-200 shadow-md space-y-6">
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
|
use App\Http\Controllers\Admin\MakerWorldController;
|
||||||
use App\Http\Controllers\CartController;
|
use App\Http\Controllers\CartController;
|
||||||
use App\Http\Controllers\CheckoutController;
|
use App\Http\Controllers\CheckoutController;
|
||||||
use App\Http\Controllers\ShopController;
|
use App\Http\Controllers\ShopController;
|
||||||
@@ -23,3 +24,16 @@ Route::get('/winkelwagen/aantal', [CartController::class, 'count'])->name('cart.
|
|||||||
Route::get('/afrekenen', [CheckoutController::class, 'index'])->name('checkout.index');
|
Route::get('/afrekenen', [CheckoutController::class, 'index'])->name('checkout.index');
|
||||||
Route::post('/afrekenen', [CheckoutController::class, 'store'])->name('checkout.store');
|
Route::post('/afrekenen', [CheckoutController::class, 'store'])->name('checkout.store');
|
||||||
Route::get('/bestelling-ontvangen/{orderNumber}', [CheckoutController::class, 'success'])->name('checkout.success');
|
Route::get('/bestelling-ontvangen/{orderNumber}', [CheckoutController::class, 'success'])->name('checkout.success');
|
||||||
|
|
||||||
|
// Admin & MakerWorld Beheer
|
||||||
|
Route::prefix('admin')->name('admin.')->group(function () {
|
||||||
|
Route::redirect('/', '/admin/makerworld');
|
||||||
|
Route::get('/makerworld', [MakerWorldController::class, 'index'])->name('makerworld.index');
|
||||||
|
Route::post('/makerworld/login', [MakerWorldController::class, 'login'])->name('makerworld.login');
|
||||||
|
Route::post('/makerworld/verify-code', [MakerWorldController::class, 'verifyCode'])->name('makerworld.verify-code');
|
||||||
|
Route::post('/makerworld/token', [MakerWorldController::class, 'saveToken'])->name('makerworld.token');
|
||||||
|
Route::post('/makerworld/disconnect', [MakerWorldController::class, 'disconnect'])->name('makerworld.disconnect');
|
||||||
|
Route::get('/makerworld/preview', [MakerWorldController::class, 'preview'])->name('makerworld.preview');
|
||||||
|
Route::post('/makerworld/import', [MakerWorldController::class, 'import'])->name('makerworld.import');
|
||||||
|
Route::post('/makerworld/batch-import', [MakerWorldController::class, 'batchImport'])->name('makerworld.batch-import');
|
||||||
|
});
|
||||||
|
|||||||
@@ -0,0 +1,205 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Tests\Feature;
|
||||||
|
|
||||||
|
use App\Models\Category;
|
||||||
|
use App\Models\Product;
|
||||||
|
use App\Models\Setting;
|
||||||
|
use App\Services\MakerWorldService;
|
||||||
|
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||||
|
use Illuminate\Support\Facades\Http;
|
||||||
|
use Tests\TestCase;
|
||||||
|
|
||||||
|
class MakerWorldImporterTest extends TestCase
|
||||||
|
{
|
||||||
|
use RefreshDatabase;
|
||||||
|
|
||||||
|
protected function fakeMakerWorldApi(): void
|
||||||
|
{
|
||||||
|
Http::fake([
|
||||||
|
'https://api.bambulab.com/v1/design-service/design/55866' => Http::response([
|
||||||
|
'id' => 55866,
|
||||||
|
'title' => 'Test Calibration Cube',
|
||||||
|
'summary' => '<p>A test calibration cube for Bambu printers.</p>',
|
||||||
|
'coverUrl' => 'https://makerworld.bblmw.com/cover.png',
|
||||||
|
'license' => 'Creative Commons',
|
||||||
|
'designCreator' => [
|
||||||
|
'name' => 'DesignerBob',
|
||||||
|
'handle' => 'designer_bob',
|
||||||
|
],
|
||||||
|
'instances' => [
|
||||||
|
[
|
||||||
|
'title' => 'Standard Profile',
|
||||||
|
'weight' => 25.4,
|
||||||
|
'prediction' => 3600, // 1 hour
|
||||||
|
],
|
||||||
|
],
|
||||||
|
'designExtension' => [
|
||||||
|
'design_pictures' => [
|
||||||
|
['url' => 'https://makerworld.bblmw.com/photo1.png'],
|
||||||
|
],
|
||||||
|
],
|
||||||
|
], 200),
|
||||||
|
'https://api.bambulab.com/v1/design-service/contest/list*' => Http::response([
|
||||||
|
'total' => 1,
|
||||||
|
'hits' => [
|
||||||
|
[
|
||||||
|
'id' => 10,
|
||||||
|
'contestName' => 'Featured Contest',
|
||||||
|
'designs' => [
|
||||||
|
[
|
||||||
|
'id' => 55866,
|
||||||
|
'title' => 'Test Calibration Cube',
|
||||||
|
'cover' => 'https://makerworld.bblmw.com/cover.png',
|
||||||
|
'designCreator' => ['name' => 'DesignerBob'],
|
||||||
|
],
|
||||||
|
],
|
||||||
|
],
|
||||||
|
],
|
||||||
|
], 200),
|
||||||
|
'https://api.bambulab.com/v1/user-service/user/login' => Http::response([
|
||||||
|
'accessToken' => 'fake_bearer_token_12345',
|
||||||
|
], 200),
|
||||||
|
'https://api.bambulab.com/v1/design-user-service/my/preference' => Http::response([
|
||||||
|
'uid' => 99999,
|
||||||
|
'name' => 'Test Bambu User',
|
||||||
|
'account' => 'test@jouwdriedee.nl',
|
||||||
|
], 200),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_it_correctly_parses_makerworld_urls_and_ids(): void
|
||||||
|
{
|
||||||
|
$service = new MakerWorldService;
|
||||||
|
|
||||||
|
$this->assertSame(55866, $service->parseModelId('55866'));
|
||||||
|
$this->assertSame(55866, $service->parseModelId('https://makerworld.com/nl/models/55866#profileId-60000'));
|
||||||
|
$this->assertSame(12345, $service->parseModelId('https://makerworld.com/en/models/12345?keyword=vase'));
|
||||||
|
$this->assertSame(789, $service->parseModelId('makerworld.com/models/789'));
|
||||||
|
$this->assertNull($service->parseModelId('invalid-url-without-id'));
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_it_manages_makerworld_access_token_in_settings(): void
|
||||||
|
{
|
||||||
|
$this->fakeMakerWorldApi();
|
||||||
|
$service = new MakerWorldService;
|
||||||
|
|
||||||
|
$this->assertFalse($service->isAuthenticated());
|
||||||
|
|
||||||
|
$service->setAccessToken('fake_bearer_token_12345');
|
||||||
|
$this->assertTrue($service->isAuthenticated());
|
||||||
|
$this->assertSame('fake_bearer_token_12345', $service->getAccessToken());
|
||||||
|
|
||||||
|
$service->logout();
|
||||||
|
$this->assertFalse($service->isAuthenticated());
|
||||||
|
$this->assertNull($service->getAccessToken());
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_admin_makerworld_dashboard_loads_successfully(): void
|
||||||
|
{
|
||||||
|
$this->fakeMakerWorldApi();
|
||||||
|
|
||||||
|
$response = $this->get(route('admin.makerworld.index', ['tab' => 'community']));
|
||||||
|
|
||||||
|
$response->assertStatus(200);
|
||||||
|
$response->assertSee('MakerWorld Product Importer');
|
||||||
|
$response->assertSee('Test Calibration Cube');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_it_provides_json_preview_for_a_model(): void
|
||||||
|
{
|
||||||
|
$this->fakeMakerWorldApi();
|
||||||
|
|
||||||
|
$response = $this->getJson(route('admin.makerworld.preview', [
|
||||||
|
'query' => 'https://makerworld.com/nl/models/55866',
|
||||||
|
]));
|
||||||
|
|
||||||
|
$response->assertStatus(200);
|
||||||
|
$response->assertJsonPath('model.makerworld_id', 55866);
|
||||||
|
$response->assertJsonPath('model.name', 'Test Calibration Cube');
|
||||||
|
$response->assertJsonPath('model.makerworld_author', 'DesignerBob');
|
||||||
|
$response->assertJsonPath('model.weight_grams', 25);
|
||||||
|
$response->assertJsonPath('model.print_time_hours', 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_it_can_import_a_model_into_the_shop(): void
|
||||||
|
{
|
||||||
|
$this->fakeMakerWorldApi();
|
||||||
|
|
||||||
|
$category = Category::create([
|
||||||
|
'name' => 'Tech & Gadgets',
|
||||||
|
'slug' => 'tech-gadgets',
|
||||||
|
]);
|
||||||
|
|
||||||
|
$response = $this->post(route('admin.makerworld.import'), [
|
||||||
|
'makerworld_id' => 55866,
|
||||||
|
'category_id' => $category->id,
|
||||||
|
'custom_price' => 19.95,
|
||||||
|
'custom_name' => 'Gekalibreerde Kubus Jouwdriedee',
|
||||||
|
'is_active' => 1,
|
||||||
|
]);
|
||||||
|
|
||||||
|
$response->assertRedirect();
|
||||||
|
$response->assertSessionHas('success');
|
||||||
|
|
||||||
|
$this->assertDatabaseHas('products', [
|
||||||
|
'makerworld_id' => 55866,
|
||||||
|
'name' => 'Gekalibreerde Kubus Jouwdriedee',
|
||||||
|
'slug' => 'gekalibreerde-kubus-jouwdriedee',
|
||||||
|
'category_id' => $category->id,
|
||||||
|
'base_price' => 19.95,
|
||||||
|
'makerworld_author' => 'DesignerBob',
|
||||||
|
'is_active' => true,
|
||||||
|
]);
|
||||||
|
|
||||||
|
$product = Product::where('makerworld_id', 55866)->first();
|
||||||
|
$this->assertNotNull($product);
|
||||||
|
|
||||||
|
// Product should be visible on webshop show route
|
||||||
|
$detailResponse = $this->get(route('product.show', $product->slug));
|
||||||
|
$detailResponse->assertStatus(200);
|
||||||
|
$detailResponse->assertSee('Gekalibreerde Kubus Jouwdriedee');
|
||||||
|
$detailResponse->assertSee('MakerWorld Model');
|
||||||
|
$detailResponse->assertSee('DesignerBob');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_it_can_batch_import_multiple_models(): void
|
||||||
|
{
|
||||||
|
$this->fakeMakerWorldApi();
|
||||||
|
|
||||||
|
$category = Category::create([
|
||||||
|
'name' => 'Tools',
|
||||||
|
'slug' => 'tools',
|
||||||
|
]);
|
||||||
|
|
||||||
|
$response = $this->post(route('admin.makerworld.batch-import'), [
|
||||||
|
'ids' => [55866],
|
||||||
|
'category_id' => $category->id,
|
||||||
|
'is_active' => 1,
|
||||||
|
]);
|
||||||
|
|
||||||
|
$response->assertRedirect();
|
||||||
|
$response->assertSessionHas('success');
|
||||||
|
|
||||||
|
$this->assertDatabaseHas('products', [
|
||||||
|
'makerworld_id' => 55866,
|
||||||
|
'category_id' => $category->id,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_it_can_save_token_and_disconnect(): void
|
||||||
|
{
|
||||||
|
$this->fakeMakerWorldApi();
|
||||||
|
|
||||||
|
$saveResponse = $this->post(route('admin.makerworld.token'), [
|
||||||
|
'token' => 'my_secret_token_12345678',
|
||||||
|
]);
|
||||||
|
|
||||||
|
$saveResponse->assertRedirect();
|
||||||
|
$this->assertSame('my_secret_token_12345678', Setting::get('makerworld_token'));
|
||||||
|
|
||||||
|
$disconnectResponse = $this->post(route('admin.makerworld.disconnect'));
|
||||||
|
$disconnectResponse->assertRedirect();
|
||||||
|
$this->assertNull(Setting::get('makerworld_token'));
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user