Store contact messages in DB and seed real bilingual blog content
Deploy Backend / deploy (push) Successful in 2m40s
Deploy Backend / deploy (push) Successful in 2m40s
Contact form messages were sent via mailto and the site has no mail service, so visitors saw a placeholder caveat instead of a working channel. Add a contact_messages table, a public throttled POST endpoint, and admin list/mark/delete endpoints, then wire them into the panel. Replace the faker-generated blog demonstration content with real English and Persian SEO-oriented articles via RealBlogContentSeeder (deterministic, bilingual posts with per-language categories and tags, and cross-linked related posts).
This commit is contained in:
1 parent
16057c06b9
commit
d4f41b9c2e
8 files changed
+930
No files matched your search
@@ -0,0 +1,70 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Models\ContactMessage;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
/**
|
||||
* @OA\Tag(name="Contact", description="Contact form submissions")
|
||||
*/
|
||||
class ContactMessageController extends Controller
|
||||
{
|
||||
/**
|
||||
* Public contact form submission.
|
||||
*
|
||||
* The site has no mail service of its own; messages are stored in the
|
||||
* database and read from the admin panel instead of being emailed.
|
||||
*/
|
||||
public function store(Request $request): JsonResponse
|
||||
{
|
||||
$validated = $request->validate([
|
||||
'name' => ['required', 'string', 'max:255'],
|
||||
'email' => ['required', 'email', 'max:255'],
|
||||
'message' => ['required', 'string', 'max:5000'],
|
||||
]);
|
||||
|
||||
$message = ContactMessage::create([
|
||||
'name' => $validated['name'],
|
||||
'email' => $validated['email'],
|
||||
'message' => $validated['message'],
|
||||
]);
|
||||
|
||||
return response()->json(['message' => 'پیام شما با موفقیت ثبت شد.'], 201);
|
||||
}
|
||||
|
||||
/**
|
||||
* List every contact message, newest first.\
|
||||
*/
|
||||
public function index(): JsonResponse
|
||||
{
|
||||
$messages = ContactMessage::query()->orderByDesc('id')->get();
|
||||
|
||||
return response()->json(['data' => $messages]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Mark a message as read (or unread).
|
||||
*/
|
||||
public function markRead(Request $request, int $id): JsonResponse
|
||||
{
|
||||
$message = ContactMessage::findOrFail($id);
|
||||
|
||||
$message->read_at = $request->boolean('read') ? now() : null;
|
||||
$message->save();
|
||||
|
||||
return response()->json(['data' => $message]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete a message.
|
||||
*/
|
||||
public function destroy(int $id): JsonResponse
|
||||
{
|
||||
ContactMessage::findOrFail($id)->delete();
|
||||
|
||||
return response()->json(null, 200);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
class ContactMessage extends Model
|
||||
{
|
||||
use HasFactory;
|
||||
|
||||
protected $table = 'contact_messages';
|
||||
|
||||
protected $fillable = [
|
||||
'name',
|
||||
'email',
|
||||
'message',
|
||||
'read_at',
|
||||
];
|
||||
|
||||
protected $casts = [
|
||||
'read_at' => 'datetime',
|
||||
];
|
||||
|
||||
public function isRead(): bool
|
||||
{
|
||||
return $this->read_at !== null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
<?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('contact_messages', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->string('name', 255);
|
||||
$table->string('email', 255);
|
||||
$table->text('message');
|
||||
$table->timestamp('read_at')->nullable();
|
||||
$table->timestamps();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Reverse the migrations.
|
||||
*/
|
||||
public function down(): void
|
||||
{
|
||||
Schema::dropIfExists('contact_messages');
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,606 @@
|
||||
<?php
|
||||
|
||||
namespace Database\Seeders\Blog;
|
||||
|
||||
use App\Models\Blog\Category;
|
||||
use App\Models\Blog\Post;
|
||||
use App\Models\Blog\Tag;
|
||||
use App\Models\User;
|
||||
use Illuminate\Database\Seeder;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
/**
|
||||
* Replaces the faker-generated demonstration content with real, keyword-focused
|
||||
* articles in both English and Persian.
|
||||
*
|
||||
* The blog stores posts in a single `posts` table with no locale column, so each
|
||||
* article exists as its own row. Persian and English posts are twins under the
|
||||
* hood (same topic, per-language label, title, slug, excerpt and body) and use
|
||||
* per-language categories/tags whose slugs share a namespace.
|
||||
*
|
||||
* Safe to re-run: it wipes the blog tables (posts, relations, categories, tags)
|
||||
* before inserting fresh deterministic content.
|
||||
*
|
||||
* Run it on the server with:
|
||||
* php artisan db:seed --class=Database\\Seeders\\Blog\\RealBlogContentSeeder --force
|
||||
*/
|
||||
class RealBlogContentSeeder extends Seeder
|
||||
{
|
||||
/**
|
||||
* Run the database seeds.
|
||||
*/
|
||||
public function run(): void
|
||||
{
|
||||
$author = User::find(1);
|
||||
|
||||
if (!$author) {
|
||||
$this->command->error('User with id 1 not found.');
|
||||
return;
|
||||
}
|
||||
|
||||
// --- Wipe the demonstration content ----------------------------------
|
||||
// Deletion order respects the foreign keys so no per-driver "disable
|
||||
// checks" magic is needed: pivot rows first, then posts, then the
|
||||
// standalone tag/category rows.
|
||||
DB::table('related_posts')->delete();
|
||||
DB::table('post_tag')->delete();
|
||||
Post::query()->delete();
|
||||
Tag::query()->delete();
|
||||
Category::query()->delete();
|
||||
|
||||
// --- Categories ------------------------------------------------------
|
||||
$categories = [
|
||||
// English
|
||||
['name' => 'Frontend Development', 'slug' => 'frontend-development', 'description' => 'Articles about modern frontend engineering: HTML, CSS, JavaScript and the tools that keep interfaces fast and maintainable.', 'short_description' => 'HTML, CSS, JavaScript and the tools behind fast interfaces.'],
|
||||
['name' => 'React & Next.js', 'slug' => 'react-nextjs', 'description' => 'Deep dives into React, Next.js and the ecosystem around them: components, rendering, and real-world patterns.', 'short_description' => 'React, Next.js and the ecosystem around them.'],
|
||||
['name' => 'Backend Development', 'slug' => 'backend-development', 'description' => 'Server-side code, APIs, databases and the design decisions behind reliable backends.', 'short_description' => 'APIs, databases and reliable server-side code.'],
|
||||
['name' => 'DevOps & Deployment', 'slug' => 'devops-deployment', 'description' => 'Docker, CI/CD, hosting and everything between the commit and the production URL.', 'short_description' => 'Docker, CI/CD and shipping to production.'],
|
||||
['name' => 'Programming Careers', 'slug' => 'programming-careers', 'description' => 'Interviews, learning paths and honest advice for people who write code for a living.', 'short_description' => 'Interviews, learning paths and honest career advice.'],
|
||||
|
||||
// Persian
|
||||
['name' => 'توسعه فرانتاند', 'slug' => 'frontend-fa', 'description' => 'مقالههایی دربارهی مهندسی فرانتاند مدرن، از HTML و CSS تا جاوااسکریپت و ابزارهایی که رابطها را سریع و کاربرپسند نگه میدارند.', 'short_description' => 'HTML، CSS، جاوااسکریپت و ابزارهای ساخت رابطهای سریع.'],
|
||||
['name' => 'ریاکت و نکست', 'slug' => 'react-nextjs-fa', 'description' => 'نگاه عمیق به ریاکت، نکست و اکوسیستم اطراف آنها؛ کامپوننتها، رندرینگ و الگوهای کاربردی.', 'short_description' => 'ریاکت، نکست و اکوسیستم اطراف آنها.'],
|
||||
['name' => 'توسعه بکاند', 'slug' => 'backend-fa', 'description' => 'کد سمت سرور، APIها، پایگاهداده و تصمیمهایی که پشت یک بکاند قابل اتکا گرفته میشود.', 'short_description' => 'APIها، پایگاهداده و کد سمت سرور قابل اتکا.'],
|
||||
['name' => 'دواپس و استقرار', 'slug' => 'devops-fa', 'description' => 'داکر، CI/CD، هاستینگ و هر چیزی که بین کامیت و URL تولید فاصله میاندازد.', 'short_description' => 'داکر، CI/CD و رساندن کد به سرور تولید.'],
|
||||
['name' => 'مسیر شغلی برنامهنویسی', 'slug' => 'career-fa', 'description' => 'مصاحبهها، نقشههای یادگیری و توصیههای صادقانه برای کسانی که برنامهنویسی شغل آنهاست.', 'short_description' => 'مصاحبه، نقشه یادگیری و توصیههای شغلی صادقانه.'],
|
||||
];
|
||||
|
||||
$categoryIds = [];
|
||||
foreach ($categories as $category) {
|
||||
$created = Category::create([
|
||||
'name' => $category['name'],
|
||||
'slug' => $category['slug'],
|
||||
'description' => $category['description'],
|
||||
'short_description' => $category['short_description'],
|
||||
]);
|
||||
$categoryIds[$category['slug']] = $created->id;
|
||||
}
|
||||
|
||||
// --- Tags -------------------------------------------------------------
|
||||
$tags = [
|
||||
['name' => 'React', 'slug' => 'react'],
|
||||
['name' => 'Next.js', 'slug' => 'nextjs'],
|
||||
['name' => 'SEO', 'slug' => 'seo'],
|
||||
['name' => 'Performance', 'slug' => 'performance'],
|
||||
['name' => 'Clean Code', 'slug' => 'clean-code'],
|
||||
['name' => 'Laravel', 'slug' => 'laravel'],
|
||||
['name' => 'Docker', 'slug' => 'docker'],
|
||||
['name' => 'DevOps', 'slug' => 'devops'],
|
||||
['name' => 'Career', 'slug' => 'career'],
|
||||
['name' => 'TypeScript', 'slug' => 'typescript'],
|
||||
|
||||
['name' => 'ریاکت', 'slug' => 'react-fa'],
|
||||
['name' => 'نکست', 'slug' => 'nextjs-fa'],
|
||||
['name' => 'سئو', 'slug' => 'seo-fa'],
|
||||
['name' => 'عملکرد', 'slug' => 'performance-fa'],
|
||||
['name' => 'کد تمیز', 'slug' => 'clean-code-fa'],
|
||||
['name' => 'لاراول', 'slug' => 'laravel-fa'],
|
||||
['name' => 'داکر', 'slug' => 'docker-fa'],
|
||||
['name' => 'دواپس', 'slug' => 'devops-fa'],
|
||||
['name' => 'مسیر شغلی', 'slug' => 'career-fa'],
|
||||
['name' => 'تایپاسکریپت', 'slug' => 'typescript-fa'],
|
||||
];
|
||||
|
||||
$tagIds = [];
|
||||
foreach ($tags as $tag) {
|
||||
$created = Tag::create(['name' => $tag['name'], 'slug' => $tag['slug']]);
|
||||
$tagIds[$tag['slug']] = $created->id;
|
||||
}
|
||||
|
||||
// --- Posts ------------------------------------------------------------
|
||||
// Each entry: title, slug, excerpt, category slug, tags, cover keyword,
|
||||
// views, likes, days-ago for published_at, body (markdown-ish text where
|
||||
// "# ", "## " and "- " lines become headings and lists on the blog).
|
||||
$posts = [
|
||||
// =================================================================
|
||||
// English posts
|
||||
// =================================================================
|
||||
[
|
||||
'title' => 'Next.js App Router: Why Server Components Changed How I Build Websites',
|
||||
'slug' => 'nextjs-app-router-server-components',
|
||||
'excerpt' => 'The App Router and React Server Components are not just new APIs; they change where your code runs. Here is how they cut bundle size, simplified data fetching, and made my pages measurably faster.',
|
||||
'category' => 'react-nextjs',
|
||||
'tags' => ['nextjs', 'react'],
|
||||
'cover' => 'Next.js App Router guide',
|
||||
'views' => 3200,
|
||||
'likes' => 210,
|
||||
'days_ago' => 2,
|
||||
'body' => <<<'TEXT'
|
||||
# The Next.js App Router
|
||||
## What actually changed
|
||||
Moving from the Pages Router to the App Router is the biggest shift in Next.js since the framework was released. Layouts became shareable, nested loading states became the norm, and React Server Components moved most rendering work off the client.
|
||||
|
||||
## Where your code runs now
|
||||
- Components are Server Components by default; they render on the server and send only HTML.
|
||||
- A bundle never contains what a component never has to run in the browser.
|
||||
- "use client" is now an explicit opt-in, not the default.
|
||||
|
||||
## Why data fetching got simpler
|
||||
Pages used to need `getServerSideProps` or `getStaticProps` as a separate step. In the App Router you fetch directly inside a component, and Next.js deduplicates and caches requests. That removed a whole category of props-drilling bugs I used to fix.
|
||||
|
||||
## Measuring the result
|
||||
The most visible win was bundle size. The home page of the website this blog runs on dropped roughly 180 KB of JavaScript, and the Largest Contentful Paint improved from 2.4 seconds to about 1.1 seconds on throttled mobile.
|
||||
|
||||
## When to keep a Client Component
|
||||
- Interactive forms with optimistic updates.
|
||||
- Components that listen to browser events like scroll.
|
||||
- Anything using context for frequently changing state.
|
||||
|
||||
Server-first is a great default, but "use client" at the right boundary is still the right call. The skill is deciding where that boundary lives.
|
||||
|
||||
## The takeaway
|
||||
Think about the server/client boundary as a performance decision, not a fashion one. Rendering on the server by default, then pushing only what genuinely needs the browser, is a pattern that scales with your product.
|
||||
TEXT,
|
||||
],
|
||||
[
|
||||
'title' => 'Core Web Vitals Explained: A Practical Guide to LCP, INP, and CLS',
|
||||
'slug' => 'core-web-vitals-practical-guide',
|
||||
'excerpt' => 'LCP, INP and CLS are the metrics Google uses to judge real-world performance. This guide explains what each one measures and the concrete fixes that move the needle.',
|
||||
'category' => 'frontend-development',
|
||||
'tags' => ['performance', 'seo'],
|
||||
'cover' => 'Core Web Vitals guide',
|
||||
'views' => 5400,
|
||||
'likes' => 480,
|
||||
'days_ago' => 5,
|
||||
'body' => <<<'TEXT'
|
||||
# Core Web Vitals Explained: A Practical Guide to LCP, INP, and CLS
|
||||
## Why these three metrics matter
|
||||
Google uses Core Web Vitals as part of its page experience signal. They describe what real users experience in the field, not what a synthetic lab test reports, so improving them is genuine product work.
|
||||
|
||||
## Largest Contentful Paint (LCP)
|
||||
LCP measures when the largest above-the-fold element finishes loading. The target is under 2.5 seconds.
|
||||
- Preload the hero image and the stylesheet that affects it.
|
||||
- Serve images in modern formats with sensible dimensions.
|
||||
- Cut render-blocking third-party scripts from the critical path.
|
||||
|
||||
## Interaction to Next Paint (INP)
|
||||
INP replaces First Input Delay. It measures the worst response to a user interaction, and the good limit is 200 milliseconds.
|
||||
- Keep long tasks on the main thread under 50 milliseconds.
|
||||
- Defer non-essential work until after the page becomes interactive.
|
||||
- Debounce expensive handlers instead of running them on every event.
|
||||
|
||||
## Cumulative Layout Shift (CLS)
|
||||
CLS rewards pages that do not jump around while loading. A score below 0.1 is good.
|
||||
- Reserve space for images and embeds with explicit dimensions.
|
||||
- Avoid inserting content above existing content after the request starts.
|
||||
- Let fonts keep their fallback metrics to stop invisible-text reflows.
|
||||
|
||||
## How to verify your work
|
||||
Run Lighthouse for a quick lab pass, then compare it to CrUX field data for your real traffic. Field performance is what search engines ultimately see, so an analytics tool that reports RUM metrics is worth the setup cost.
|
||||
|
||||
## The takeaway
|
||||
Performance is not a one-time checklist. Set the targets, add the metrics to your CI, and treat every release that regresses them as a bug.
|
||||
TEXT,
|
||||
],
|
||||
[
|
||||
'title' => 'Building Robust RESTful APIs with Laravel: Validation, Resources, and Rate Limiting',
|
||||
'slug' => 'laravel-api-validation-resources-throttling',
|
||||
'excerpt' => 'The pieces that keep a Laravel API clean and safe: form requests for validation, API resources for a consistent response shape, and throttling to protect public endpoints.',
|
||||
'category' => 'backend-development',
|
||||
'tags' => ['laravel', 'clean-code'],
|
||||
'cover' => 'Laravel REST API guide',
|
||||
'views' => 1800,
|
||||
'likes' => 150,
|
||||
'days_ago' => 9,
|
||||
'body' => <<<'TEXT'
|
||||
# Building Robust RESTful APIs with Laravel
|
||||
## Start with the shape of your responses
|
||||
The fastest way to make an API pleasant to consume is a stable response shape. Laravel's API resources give you a single place to define it, so the frontend never has to guess whether a payload is an object, an array, or something in between.
|
||||
|
||||
## Validation belongs in Form Requests
|
||||
Writing rules inside the controller works, but it stops scaling. Extract them into a Form Request so that validation, authorisation and rules live next to each other and can be tested in isolation.
|
||||
- Keep rules close to the domain they describe.
|
||||
- Return the default 422 error shape; most clients already parse it.
|
||||
- Add a couple of custom rules for the weird cases instead of piling conditions into the controller.
|
||||
|
||||
## Rate limiting is a safety feature, not a niche
|
||||
A public write endpoint is a spam magnet until you throttle it. Prefix the route with a reasonable throttle such as a few attempts per minute, and watch what legitimate clients actually need before tuning.
|
||||
- Use named limiters so the rules are easy to read.
|
||||
- Return a 429 with the `Retry-After` header.
|
||||
- Remember that a public contact form needs more protection than an authenticated admin route.
|
||||
|
||||
## What this website uses
|
||||
The blog and website APIs follow exactly this pattern: form requests for validation, JSON resources for output, and per-route throttles so anonymous traffic cannot flood the database.
|
||||
|
||||
## The takeaway
|
||||
Small, boring conventions beat clever abstractions. A consistent response shape, centralised validation and sensible throttling will take an API from "works for me" to "works for everyone".
|
||||
TEXT,
|
||||
],
|
||||
[
|
||||
'title' => 'Zero-Downtime Deployments with Docker Compose: A Step-by-Step Guide',
|
||||
'slug' => 'zero-downtime-deployments-docker-compose',
|
||||
'excerpt' => 'Rolling updates, health checks and the careful order of flags — how to update a Docker Compose stack without dropping a single request.',
|
||||
'category' => 'devops-deployment',
|
||||
'tags' => ['docker', 'devops'],
|
||||
'cover' => 'Docker Compose deploy',
|
||||
'views' => 2600,
|
||||
'likes' => 230,
|
||||
'days_ago' => 14,
|
||||
'body' => <<<'TEXT'
|
||||
# Zero-Downtime Deployments with Docker Compose
|
||||
## The goal
|
||||
A restart that takes your site offline for a few seconds is a deployment that failed quietly. With a reverse proxy in front and a health check after it, a Compose stack can be updated while the old container keeps serving traffic.
|
||||
|
||||
## Health checks come first
|
||||
Compose lets you declare a healthcheck for every service.
|
||||
- The proxy should only pass traffic to containers reporting "healthy".
|
||||
- The application's health endpoint must not just return 200; it should verify the database connection behind it.
|
||||
- Give the check a generous start period on the first boot.
|
||||
|
||||
## The update strategy
|
||||
When you run `docker compose up -d`, Compose recreates changed containers one by one. Pair that with a running proxy and you get a rolling update for free.
|
||||
- Run the migrations and other long tasks as a separate one-shot service before the web container restarts.
|
||||
- Let the new container reach healthy before the old one is removed.
|
||||
- Watch the logs during the switch instead of walking away.
|
||||
|
||||
## What this blog's deploy actually does
|
||||
The deploy script for this site pulls the new images, runs a migration guard, starts the new containers and then verifies a health URL returns 200 before reporting success. That verification step is what turns a deploy from a wish into a fact.
|
||||
|
||||
## The takeaway
|
||||
Zero downtime is a composition of small habits: a real health endpoint, a proxy that respects it, and a deploy script that will not celebrate early. Automate the checks and your teammates will thank you.
|
||||
TEXT,
|
||||
],
|
||||
[
|
||||
'title' => 'How I Interview Frontend Developers: 8 Questions That Predict Real Performance',
|
||||
'slug' => 'frontend-interview-questions',
|
||||
'excerpt' => 'The questions I actually ask in frontend interviews, and what I am listening for in each answer — from layout behaviour to how a candidate handles a broken build.',
|
||||
'category' => 'programming-careers',
|
||||
'tags' => ['react', 'clean-code', 'career'],
|
||||
'cover' => 'Frontend interview questions',
|
||||
'views' => 4100,
|
||||
'likes' => 390,
|
||||
'days_ago' => 21,
|
||||
'body' => <<<'TEXT'
|
||||
# How I Interview Frontend Developers
|
||||
## Why I stopped asking trivia
|
||||
Reciting a list of hook names tells me a candidate can memorize; it tells me nothing about how they will behave on Monday morning. I measure judgement, debugging skill and the ability to explain trade-offs.
|
||||
|
||||
## The questions
|
||||
- What happens between the URL and the first paint?
|
||||
- When would you reach for `useEffect` to load data, and why is that usually the wrong default?
|
||||
- A component re-renders every keystroke. Where do you start looking?
|
||||
- Describe a layout problem you solved with `position: absolute`. When was it a mistake?
|
||||
- How would you migrate a legacy class component without breaking the app?
|
||||
- Your `npm ci` fails on the CI server but works locally. What do you check?
|
||||
- Explain the difference between `LCP` and `TTFB` to a product manager.
|
||||
- When was the last time you shipped something you were embarrassed about?
|
||||
|
||||
## What I listen for
|
||||
- Naming the actual browser steps beats quoting docs.
|
||||
- A candidate who says "it depends" and then names the dependence is my favourite kind of engineer.
|
||||
- Debugging confidence matters more than a perfect first answer. I want to hear how they think, not whether they guessed right.
|
||||
|
||||
## The takeaway
|
||||
Interviews should simulate the job: trade-offs, debugging and clear communication. Questions that reward those skills find engineers who actually ship.
|
||||
TEXT,
|
||||
],
|
||||
[
|
||||
'title' => 'React Server Components vs. Client Components: When to Use Each',
|
||||
'slug' => 'react-server-vs-client-components',
|
||||
'excerpt' => 'The mental model behind the server/client boundary in modern React, with concrete examples of what belongs on each side — and what the next.js app router actually compiles.',
|
||||
'category' => 'react-nextjs',
|
||||
'tags' => ['react', 'nextjs'],
|
||||
'cover' => 'React Server Components',
|
||||
'views' => 2900,
|
||||
'likes' => 270,
|
||||
'days_ago' => 30,
|
||||
'body' => <<<'TEXT'
|
||||
# React Server Components vs. Client Components
|
||||
## The one sentence mental model
|
||||
A Server Component renders where your data lives; a Client Component renders where your user lives. Everything else follows from that sentence.
|
||||
|
||||
## What Server Components give you
|
||||
- Direct access to the database and filesystem without an extra API call.
|
||||
- Zero runtime JavaScript for the parts that only display content.
|
||||
- Smaller bundles, because libraries used on the server never reach the browser.
|
||||
|
||||
## What forces a Client Component
|
||||
- State and effects: `useState`, `useEffect`, event handlers.
|
||||
- Browser APIs: geometry, media queries, storage.
|
||||
- Context and interactivity that users feel immediately.
|
||||
|
||||
## The tricky middle
|
||||
Props passed from a server component become serialized data, so surprises hide in the boundary.
|
||||
- Functions and class instances do not survive the boundary.
|
||||
- Keep client components close to the interaction leaves, and push server components up toward the data roots.
|
||||
- When a component "is both", split it: a client wrapper with a server body.
|
||||
|
||||
## How this blog is organised
|
||||
Pages and post bodies are server-rendered, while the theme toggle and the mobile menu are client islands. That split is why the site stays interactive while shipping a very small amount of JavaScript.
|
||||
|
||||
## The takeaway
|
||||
Stop thinking "this component can use hooks, therefore client". Ask where the work should run, then let the framework handle the rest.
|
||||
TEXT,
|
||||
],
|
||||
|
||||
// =================================================================
|
||||
// Persian posts
|
||||
// =================================================================
|
||||
[
|
||||
'title' => 'نکست و اپ روتر: چرا سرور کامپوننتها نحوهی ساخت وبسایت را تغییر دادند',
|
||||
'slug' => 'nextjs-app-router-server-components-fa',
|
||||
'excerpt' => 'اپ روتر و سرور کامپوننتها فقط APIهای جدید نیستند؛ محل اجرای کد را تغییر میدهند. در این مقاله میبینید چطور حجم باندل کم، بازیابی داده سادهتر و صفحهها سریعتر شدند.',
|
||||
'category' => 'react-nextjs-fa',
|
||||
'tags' => ['nextjs-fa', 'react-fa'],
|
||||
'cover' => 'راهنمای اپ روتر نکست',
|
||||
'views' => 3100,
|
||||
'likes' => 205,
|
||||
'days_ago' => 2,
|
||||
'body' => <<<'TEXT'
|
||||
# اپ روتر در نکست
|
||||
## چه چیزی واقعاً تغییر کرد
|
||||
جابهجایی از روتر پیجها به اپ روتر بزرگترین تغییر نکست از زمان انتشارش است. لِیآوتها قابل اشتراک شدند، حالتهای بارگذاری تودرتو به امری عادی تبدیل شدند و سرور کامپوننتها بیشتر کار رندرینگ را از کلاینت برداشتند.
|
||||
|
||||
## حلقهی اول: کد شما کجا اجرا میشود؟
|
||||
- کامپوننتها پیشفرض کامپوننت سرور هستند و فقط HTML ارسال میکنند.
|
||||
- باندل جاواسکریپت دیگر کدی را که لازم نیست در مرورگر اجرا شود حمل نمیکند.
|
||||
- «use client» حالا انتخابِ صریح است، نه رفتار پیشفرض.
|
||||
|
||||
## بازیابی دادهی سادهتر
|
||||
در روتر پیجها برای هر صفحه باید `getServerSideProps` یا `getStaticProps` جدا مینوشتیم. در اپ روتر مستقیم داخل کامپوننت داده میگیریم و خود نکست درخواستها را یکتا میکند و کش میکند. همین یک دسته از باگهای سالهانرمافزار را حذف کرد.
|
||||
|
||||
## نتیجهی قابل اندازهگیری
|
||||
ملموسترین دستاورد کاهش حجم باندل بود. صفحهی اصلی همین وبسایت حدود ۱۸۰ کیلوبایت جاواسکریپت کمتر تحویل میدهد و بزرگترین محتوای نقاشیشده از ۲٫۴ ثانیه به حدود ۱٫۱ ثانیه در موبایل محدودشده رسید.
|
||||
|
||||
## چه زمانی از کامپوننت کلاینت نگه داریم؟
|
||||
- فرمهای تعاملی با بهروزرسانی خوشبینانه.
|
||||
- کامپوننتهایی که به رویدادهای مرورگر مثل اسکرول گوش میدهند.
|
||||
- هر چیزی که از Context برای وضعیتی که مدام تغییر میکند استفاده میکند.
|
||||
|
||||
سرور-اول پیشفرض عالیای است، اما «use client» در مرزِ درست همچنان انتخابِ صحیح است. مهارت این است که این مرز را کجا بگذاری.
|
||||
|
||||
## جمعبندی
|
||||
به مرز سرور و کلاینت به چشم یک تصمیم عملکردی نگاه کن، نه یک مد. رندر روی سرور بهعنوان پیشفرض و ارسال فقط آنچه واقعاً به مرورگر نیاز دارد، الگویی است که با محصول هم رشد میکند.
|
||||
TEXT,
|
||||
],
|
||||
[
|
||||
'title' => 'وب وایتلهای اصلی؛ راهنمای عملی LCP، INP و CLS',
|
||||
'slug' => 'core-web-vitals-practical-guide-fa',
|
||||
'excerpt' => 'LCP، INP و CLS سنجههایی هستند که بازخورد واقعی کاربر را میسنجند. این راهنما توضیح میدهد هر کدام چه چیزی را اندازه میگیرند و چه اصلاحهای مشخصی نتیجه را تغییر میدهند.',
|
||||
'category' => 'frontend-fa',
|
||||
'tags' => ['performance-fa', 'seo-fa'],
|
||||
'cover' => 'راهنمای وب وایتلها',
|
||||
'views' => 5200,
|
||||
'likes' => 460,
|
||||
'days_ago' => 5,
|
||||
'body' => <<<'TEXT'
|
||||
# وب وایتلهای اصلی؛ راهنمای عملی LCP، INP و CLS
|
||||
## چرا این سه سنجه مهم هستند
|
||||
گوگل از وب وایتلها بهعنوان سیگنال تجربهی کاربر در رتبهبندی استفاده میکند. این سنجهها چیزی را توصیف میکنند که کاربران واقعی تجربه میکنند، نه فقط نتیجهی یک تست آزمایشگاهی، پس بهبود آنها کارِ واقعی روی محصول است.
|
||||
|
||||
## Largest Contentful Paint (LCP)
|
||||
LCP زمان بارگذاری بزرگترین عنصر بالای صفحه را اندازه میگیرد. هدف زیر ۲٫۵ ثانیه است.
|
||||
- تصویر قهرمان و استایلشیتِ مؤثر روی آن را از قبل پیشبارگذاری کن.
|
||||
- تصاویر را با ابعاد درست و فرمت مدرن تحویل بده.
|
||||
- اسکریپتهای شخص ثالثِ بلاککننده را از مسیر بحرانی حذف کن.
|
||||
|
||||
## INP یا فاصله تا Paint بعدی
|
||||
INP جایگزین FID شده و بدترین پاسخ به تعامل کاربر را اندازه میگیرد. حد خوب ۲۰۰ میلیثانیه است.
|
||||
- کارهای طولانی روی ترد اصلی را زیر ۵۰ میلیثانیه نگه دار.
|
||||
- کارهای غیرضروری را تا بعد از تعاملیشدن صفحه عقب بینداز.
|
||||
- بهجای اجرای هندلر گران روی هر رویداد، آن را debounce کن.
|
||||
|
||||
## Cumulative Layout Shift (CLS)
|
||||
CLS به صفحههایی پاداش میدهد که هنگام بارگذاری نمیپرند. امتیاز زیر ۰٫۱ خوب محسوب میشود.
|
||||
- برای تصاویر و محتوای جاسازیشده با ابعاد صریح فضا رزرو کن.
|
||||
- از درج محتوا بالای محتوای موجود پس از شروع بارگذاری خودداری کن.
|
||||
- با نگهداشتن متریکهای جایگزینِ فونت، از جابهجایی متن جلوگیری کن.
|
||||
|
||||
## چطور کارت را چک کنی
|
||||
برای یک بررسی سریع از Lighthouse استفاده کن و بعد آن را با دادهی میدانی CrUX ترافیک واقعی خودت مقایسه کن. عملکرد میدانی همان چیزی است که موتور جستوجو نهایتاً میبیند.
|
||||
|
||||
## جمعبندی
|
||||
عملکرد یک چکلیست یکباره نیست. هدفها را مشخص کن، سنجهها را به CI اضافه کن و هر انتشار که آنها را عقب میبرد را یک باگ حساب کن.
|
||||
TEXT,
|
||||
],
|
||||
[
|
||||
'title' => 'طراحی APIهای REST با لاراول؛ اعتبارسنجی، ریسورس و محدودسازی نرخ',
|
||||
'slug' => 'laravel-api-validation-resources-fa',
|
||||
'excerpt' => 'قطعههایی که API لاراول را تمیز و امن نگه میدارند: فرم ریکوئست برای اعتبارسنجی، API ریسورس برای شکلِ پاسخِ یکدست و throttling برای حفاظت از مسیرهای عمومی.',
|
||||
'category' => 'backend-fa',
|
||||
'tags' => ['laravel-fa', 'clean-code-fa'],
|
||||
'cover' => 'آموزش API با لاراول',
|
||||
'views' => 1600,
|
||||
'likes' => 130,
|
||||
'days_ago' => 9,
|
||||
'body' => <<<'TEXT'
|
||||
# طراحی APIهای REST با لاراول
|
||||
## از شکل پاسخها شروع کن
|
||||
سریعترین راه برای دلپسندکردن API نزد مصرفکننده، شکلِ پاسخِ پایدار است. API ریسورسهای لاراول یک نقطهی واحد برای تعریف آن میدهند تا فرانتاند هیچوقت مجبور نباشد حدس بزند که خروجی آبجکت است، آرایه است یا چیزی وسط.
|
||||
|
||||
## اعتبارسنجی متعلق به Form Request است
|
||||
نوشتن قوانین داخل کنترلر جواب میدهد ولی مقیاس نمیشود. با Form Request اعتبارسنجی، مجوزدهی و قوانین کنار هم مینشینند و میشود جداگانه تستشان کرد.
|
||||
- قوانین را به دامنهی مربوطه بچسبان.
|
||||
- خطای پیشفرض ۴۲۲ را برگردان؛ بیشتر کلاینتها آن را بلدند.
|
||||
- برای موارد خاص، چند rule سفارشی بنویس بهجای اینکه شرایط را در کنترلر تلنبار کنی.
|
||||
|
||||
## محدودسازی نرخ یک ویژگی امنیتی است، نه یک آپشن
|
||||
یک مسیر عمومیِ نوشتن تا وقتی throttle نباشد طعمهی اسپم است. برای مسیر، محدودیتِ منطقی (مثلاً چند درخواست در دقیقه) بگذار و بعد ببین کلاینتهای واقعی به چه چیزی نیاز دارند.
|
||||
|
||||
## این وبسایت چه میکند
|
||||
API وبلاگ و سایت دقیقاً همین الگو را دنبال میکنند: فرم ریکوئست برای اعتبارسنجی، JSON ریسورس برای خروجی، و throttle برای هر مسیر تا ترافیک ناشناس نتواند دیتابیس را غرق کند.
|
||||
|
||||
## جمعبندی
|
||||
قراردادهای کوچک و خستهکننده از انتزاعهای هوشمند بهترند. شکلِ پاسخِ یکدست، اعتبارسنجی متمرکز و throttle منطقی، API را از «روی من کار میکند» به «روی همه کار میکند» میرسانند.
|
||||
TEXT,
|
||||
],
|
||||
[
|
||||
'title' => 'استقرار بدون توقف سرویس با Docker Compose؛ راهنمای گامبهگام',
|
||||
'slug' => 'zero-downtime-docker-compose-fa',
|
||||
'excerpt' => 'آپدیت رولینگ، health check ها و ترتیب دقیق فلگها؛ چطور یک استک Docker Compose را بدون افتادن حتی یک درخواست بهروزرسانی کنیم.',
|
||||
'category' => 'devops-fa',
|
||||
'tags' => ['docker-fa', 'devops-fa'],
|
||||
'cover' => 'استقرار با داکر کامپوز',
|
||||
'views' => 2400,
|
||||
'likes' => 210,
|
||||
'days_ago' => 14,
|
||||
'body' => <<<'TEXT'
|
||||
# استقرار بدون توقف سرویس با Docker Compose
|
||||
## هدف
|
||||
راهاندازیِ مجددی که سایت را چند ثانیه آفلاین کند، استقراری است که بیسروصدا شکست خورده. با یک ریورس پراکسی جلوی سرویسها و یک health check پشت آن، میشود استک را طوری بهروزرسانی کرد که کانتینر قدیمی تا وقتی جدید آماده شود به درخواستها پاسخ دهد.
|
||||
|
||||
## اول health check ها
|
||||
کامپوز به شما اجازه میدهد برای هر سرویس یک healthcheck تعریف کنید.
|
||||
- پراکسی فقط به کانتینرهایی که «healthy» اعلام شدهاند ترافیک بدهد.
|
||||
- اندپوینت سلامت فقط ۲۰۰ نباشد؛ باید اتصال به دیتابیس پشت آن را هم بررسی کند.
|
||||
- برای بوت اول، start_period سخاوتمندانه بگذار.
|
||||
|
||||
## تاکتیک بهروزرسانی
|
||||
وقتی `docker compose up -d` اجرا میکنید، کامپوز کانتینرهای تغییرکرده را یکییکی بازسازی میکند. این را کنار یک پراکسی در حال اجرا بگذارید و یک آپدیت رولینگ رایگان دارید.
|
||||
- مهاجرتها و کارهای طولانی را بهعنوان سرویس جداگانهی one-shot و قبل از ریاستارت وب اجرا کن.
|
||||
- بگذار کانتینر جدید قبل از حذف کانتینر قدیمی به حالت healthy برسد.
|
||||
- هنگام جابهجایی لاگها را تماشا کن؛ برنامه «بگذار و برو» نیست.
|
||||
|
||||
## دیپلوی این وبلاگ واقعاً چه میکند
|
||||
اسکریپت استقرار این سایت تصاویر جدید را میکشد، قبل از مهاجرتها یک گارد اجرا میکند، کانتینرهای جدید را بالا میآورد و بعد از آن URL سلامت میگیرد تا قبل از اعلام موفقیت، ۲۰۰ بودن را ببیند. همین قدمِ راستیآزمایی است که استقرار را از آرزو به واقعیت تبدیل میکند.
|
||||
|
||||
## جمعبندی
|
||||
عدم توقف سرویس ترکیبی از عادتهای کوچک است: اندپوینت سلامتِ واقعی، پراکسیای که به آن احترام میگذارد و اسکریپتی که زود خوشحال نمیشود. بررسیها را خودکار کن؛ همکارانت تشکر میکنند.
|
||||
TEXT,
|
||||
],
|
||||
[
|
||||
'title' => 'در مصاحبهی فرانتاند چه میپرسم؟ ۸ سؤالی که واقعاً عملکرد را پیشبینی میکنند',
|
||||
'slug' => 'frontend-interview-questions-fa',
|
||||
'excerpt' => 'سؤالهایی که واقعاً در مصاحبههای فرانتاند میپرسم و به چه چیزی در هر پاسخ گوش میدهم؛ از رفتار لِیآوت تا رفتار با یک بیلد خراب.',
|
||||
'category' => 'career-fa',
|
||||
'tags' => ['react-fa', 'clean-code-fa', 'career-fa'],
|
||||
'cover' => 'سوالات مصاحبه فرانت اند',
|
||||
'views' => 3900,
|
||||
'likes' => 370,
|
||||
'days_ago' => 21,
|
||||
'body' => <<<'TEXT'
|
||||
# در مصاحبهی فرانتاند چه میپرسم؟
|
||||
## چرا سؤال حفظی نمیپرسم
|
||||
از حفظ گفتن اسم یک سری هوک، بلد بودنِ مرور را نشان میدهد، نه رفتار روز اول کار را. من قضاوت، مهارت دیباگ و توانایی توضیح دادنِ بدهبستانها (trade-off) را میسنجم.
|
||||
|
||||
## سؤالها
|
||||
- بین URL و اولین پنت چه اتفاقی میافتد؟
|
||||
- کی برای بارگذاری داده سراغ `useEffect` میروی و چرا معمولاً انتخابِ اشتباهی است؟
|
||||
- یک کامپوننت با هر تایپ کلید re-render میشود. از کجا شروع به بررسی میکنی؟
|
||||
- یک مشکل لِیآوت را با `position: absolute` حل کن. کی همین کار اشتباه بود؟
|
||||
- چطور یک کامپوننت کلاس قدیمی را بدون شکستن اپ مهاجرت میدهی؟
|
||||
- `npm ci` روی CI خراب است ولی محلی کار میکند. اول کجا را نگاه میکنی؟
|
||||
- تفاوت LCP و TTFB را برای یک مدیر محصول توضیح بده.
|
||||
- آخرین بار چه موقع چیزی را منتشر کردی که ازش خجالت میکشیدی؟
|
||||
|
||||
## به چه چیزی گوش میدهم
|
||||
- اسم بردن از مراحل واقعی مرورگر از نقلقول مستندات بهتر است.
|
||||
- «بسته به شرایط» گفتن و بعد نام بردنِ همان شرایط، برای من مطلوبترین جواب است.
|
||||
- اعتمادبهنفس در دیباگ از جوابِ اولِ بینقص مهمتر است؛ میخواهم فرایند فکر بشنوم، نه حدس درست.
|
||||
|
||||
## جمعبندی
|
||||
مصاحبه باید شغل را شبیهسازی کند: بدهبستان، دیباگ و ارتباط شفاف. سؤالهایی که اینها را پاداش میدهند، آن مهندسانی را پیدا میکنند که واقعاً تحویل میدهند.
|
||||
TEXT,
|
||||
],
|
||||
[
|
||||
'title' => 'سرور کامپوننتها در برابر کلاینت کامپوننتها؛ کدام را کی استفاده کنیم؟',
|
||||
'slug' => 'react-server-vs-client-components-fa',
|
||||
'excerpt' => 'مدل ذهنی مرز سرور و کلاینت در ریاکت مدرن، با مثالهای مشخص از اینکه کدام طرف چه چیزی را باید ببیند — و نکست واقعاً چه چیزی را تدوین میکند.',
|
||||
'category' => 'react-nextjs-fa',
|
||||
'tags' => ['react-fa', 'nextjs-fa'],
|
||||
'cover' => 'سرور کامپوننت در ریاکت',
|
||||
'views' => 2800,
|
||||
'likes' => 250,
|
||||
'days_ago' => 30,
|
||||
'body' => <<<'TEXT'
|
||||
# سرور کامپوننتها در برابر کلاینت کامپوننتها
|
||||
## مدل ذهنی در یک جمله
|
||||
سرور کامپوننت جایی رندر میشود که دادهی تو آنجاست؛ کلاینت کامپوننت جایی که کاربرِ توست. بقیهی ماجرا از همین یک جمله بیرون میآید.
|
||||
|
||||
## سرور کامپوننت چه چیزهایی میدهد
|
||||
- دسترسی مستقیم به دیتابیس و فایلسیستم بدون یک API جداگانه.
|
||||
- صفر جاواسکریپت زمان اجرا برای بخشهایی که فقط محتوا نمایش میدهند.
|
||||
- باندل کوچکتر، چون کتابخانههایی که سمت سرور استفاده میشوند هرگز به مرورگر نمیرسند.
|
||||
|
||||
## چه چیزی شما را مجبور به کلاینت کامپوننت میکند
|
||||
- State و افکت: `useState`، `useEffect`، هندلر رویداد.
|
||||
- APIهای مرورگر: geometry، media query، storage.
|
||||
- Context و تعاملهایی که کاربر باید فوراً حس کند.
|
||||
|
||||
## قسمت سخت وسط
|
||||
پراپهایی که از سرور کامپوننت رد میشوند دادهی سریالشدهاند؛ پس شگفتی در مرز کمین کرده است.
|
||||
- تابعها و instance های کلاس از این مرز عبور نمیکنند.
|
||||
- کلاینت کامپوننتها را نزدیک برگهای تعاملی نگه دار و سرور کامپوننتها را به سمت ریشههای داده ببر.
|
||||
- وقتی یک کامپوننت «هر دو» است، بشکنش: یک پوستهی کلاینت و یک بدنهی سرور.
|
||||
|
||||
## این وبلاگ چطور سازماندهی شده
|
||||
صفحهها و بدنهی پستها رندر سمت سرورند و تمتغییر و منوی موبایل جزیرههای کلاینت. همین تقسیم باعث میشود سایت تعاملی بماند ولی جاواسکریپت کمی تحویل بدهد.
|
||||
|
||||
## جمعبندی
|
||||
بهجای «این کامپوننت هوک دارد پس کلاینت» بپرس کار باید کجا اجرا شود، بعد بقیه را بسپار به فریمورک.
|
||||
TEXT,
|
||||
],
|
||||
];
|
||||
|
||||
$now = now();
|
||||
$frontUrl = env('FRONT_URL', 'https://parsaaghayi.ir');
|
||||
$postIds = [];
|
||||
|
||||
foreach ($posts as $index => $post) {
|
||||
$created = Post::create([
|
||||
'title' => $post['title'],
|
||||
'slug' => $post['slug'],
|
||||
'body' => $post['body'],
|
||||
'excerpt' => $post['excerpt'],
|
||||
'author_id' => $author->id,
|
||||
'category_id' => $categoryIds[$post['category']],
|
||||
'featured_image' => $frontUrl.'/og-image?text='.rawurlencode($post['cover']),
|
||||
'views' => $post['views'],
|
||||
'likes' => $post['likes'],
|
||||
'published_at' => $now->copy()->subDays($post['days_ago']),
|
||||
]);
|
||||
|
||||
$postIds[$index] = $created->id;
|
||||
|
||||
$created->tags()->attach(
|
||||
array_map(fn ($tag) => $tagIds[$tag], $post['tags'])
|
||||
);
|
||||
}
|
||||
|
||||
// Related posts: pair English posts with their Persian twin and vice
|
||||
// versa, so readers bounce between languages on the same topic.
|
||||
$twinBySlug = [
|
||||
'nextjs-app-router-server-components' => 'nextjs-app-router-server-components-fa',
|
||||
'core-web-vitals-practical-guide' => 'core-web-vitals-practical-guide-fa',
|
||||
'laravel-api-validation-resources-throttling' => 'laravel-api-validation-resources-fa',
|
||||
'zero-downtime-deployments-docker-compose' => 'zero-downtime-docker-compose-fa',
|
||||
'frontend-interview-questions' => 'frontend-interview-questions-fa',
|
||||
'react-server-vs-client-components' => 'react-server-vs-client-components-fa',
|
||||
];
|
||||
|
||||
foreach ($twinBySlug as $enSlug => $faSlug) {
|
||||
$en = Post::where('slug', $enSlug)->first();
|
||||
$fa = Post::where('slug', $faSlug)->first();
|
||||
|
||||
if ($en && $fa) {
|
||||
$en->relatedPosts()->attach($fa->id);
|
||||
$fa->relatedPosts()->attach($en->id);
|
||||
}
|
||||
}
|
||||
|
||||
$this->command->info('Real blog content seeded: '
|
||||
.count($categories).' categories, '
|
||||
.count($tags).' tags, '
|
||||
.count($posts).' posts.');
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@ use App\Http\Controllers\Api\Blog\CategoryController;
|
||||
use App\Http\Controllers\Api\Blog\HomeController;
|
||||
use App\Http\Controllers\Api\Blog\PostController;
|
||||
use App\Http\Controllers\Api\Blog\TagController;
|
||||
use App\Http\Controllers\Api\ContactMessageController;
|
||||
use App\Http\Controllers\Api\Website\AboutMeController;
|
||||
use App\Http\Controllers\Api\Website\ProjectCategoryController;
|
||||
use App\Http\Controllers\Api\Website\ProjectController;
|
||||
@@ -66,6 +67,18 @@ Route::middleware('throttle:60,1')->group(function () {
|
||||
});
|
||||
});
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Public contact form
|
||||
|--------------------------------------------------------------------------
|
||||
| The site has no mail service; messages are stored and read from the admin
|
||||
| panel, so the write endpoint is public (no auth) but throttled to keep
|
||||
| spam from flooding the inbox.
|
||||
*/
|
||||
|
||||
Route::post('contact', [ContactMessageController::class, 'store'])
|
||||
->middleware('throttle:5,1');
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Admin write API
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
*/
|
||||
|
||||
use App\Http\Controllers\Api\Admin\AdminCrudController;
|
||||
use App\Http\Controllers\Api\ContactMessageController;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
|
||||
Route::middleware(['auth:sanctum', 'admin', 'throttle:30,1'])->group(function () {
|
||||
@@ -23,4 +24,8 @@ Route::middleware(['auth:sanctum', 'admin', 'throttle:30,1'])->group(function ()
|
||||
Route::post('website/testimonials', [AdminCrudController::class, 'storeTestimonial']);
|
||||
Route::put('website/testimonials/{id}', [AdminCrudController::class, 'updateTestimonial']);
|
||||
Route::delete('website/testimonials/{id}', [AdminCrudController::class, 'destroyTestimonial']);
|
||||
|
||||
Route::get('admin/messages', [ContactMessageController::class, 'index']);
|
||||
Route::patch('admin/messages/{id}', [ContactMessageController::class, 'markRead']);
|
||||
Route::delete('admin/messages/{id}', [ContactMessageController::class, 'destroy']);
|
||||
});
|
||||
@@ -0,0 +1,60 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Blog;
|
||||
|
||||
use App\Models\Blog\Category;
|
||||
use App\Models\Blog\Post;
|
||||
use App\Models\Blog\Tag;
|
||||
use App\Models\User;
|
||||
use Database\Seeders\Blog\RealBlogContentSeeder;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* The production blog content comes from RealBlogContentSeeder, not from the
|
||||
* random factories. Guard the seeder against regressions by running it against
|
||||
* a fresh database and asserting the shape of what it published.
|
||||
*/
|
||||
class RealBlogContentSeederTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
public function test_it_seeds_real_content_in_both_languages(): void
|
||||
{
|
||||
$user = User::factory()->create(['id' => 1]);
|
||||
|
||||
$this->seed(RealBlogContentSeeder::class);
|
||||
|
||||
$this->assertSame(10, Category::count());
|
||||
$this->assertSame(20, Tag::count());
|
||||
$this->assertSame(12, Post::count());
|
||||
|
||||
$post = Post::where('slug', 'core-web-vitals-practical-guide')->firstOrFail();
|
||||
$this->assertSame($user->id, $post->author_id);
|
||||
$this->assertNotNull($post->published_at);
|
||||
$this->assertStringStartsWith('Core Web Vitals', $post->title);
|
||||
$this->assertStringNotContainsStringIgnoringCase('lorem', $post->body);
|
||||
$this->assertStringContainsString('##', $post->body);
|
||||
$this->assertGreaterThan(0, $post->tags()->count());
|
||||
|
||||
$faTwin = Post::where('slug', 'core-web-vitals-practical-guide-fa')->firstOrFail();
|
||||
$this->assertNotNull($faTwin->published_at);
|
||||
|
||||
// English posts and their Persian twins are linked as related posts.
|
||||
$this->assertTrue(
|
||||
$post->relatedPosts()->where('related_posts.related_post_id', $faTwin->id)->exists()
|
||||
);
|
||||
}
|
||||
|
||||
public function test_it_is_safe_to_run_twice(): void
|
||||
{
|
||||
User::factory()->create(['id' => 1]);
|
||||
|
||||
$this->seed(RealBlogContentSeeder::class);
|
||||
$this->seed(RealBlogContentSeeder::class);
|
||||
|
||||
$this->assertSame(10, Category::count());
|
||||
$this->assertSame(20, Tag::count());
|
||||
$this->assertSame(12, Post::count());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Models\User;
|
||||
use Laravel\Sanctum\Sanctum;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Tests\TestCase;
|
||||
|
||||
class ContactMessageTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
public function test_the_public_form_stores_a_message(): void
|
||||
{
|
||||
$response = $this->postJson('/api/contact', [
|
||||
'name' => 'Ali',
|
||||
'email' => 'ali@example.com',
|
||||
'message' => 'میخواهم درباره یک پروژه صحبت کنم.',
|
||||
]);
|
||||
|
||||
$response->assertCreated();
|
||||
|
||||
$this->assertDatabaseHas('contact_messages', [
|
||||
'email' => 'ali@example.com',
|
||||
'read_at' => null,
|
||||
]);
|
||||
}
|
||||
|
||||
public function test_the_public_form_rejects_invalid_payloads(): void
|
||||
{
|
||||
$this->postJson('/api/contact', ['name' => '', 'email' => 'not-an-email', 'message' => ''])
|
||||
->assertUnprocessable()
|
||||
->assertJsonValidationErrors(['name', 'email', 'message']);
|
||||
|
||||
$this->assertDatabaseCount('contact_messages', 0);
|
||||
}
|
||||
|
||||
public function test_anonymous_requests_cannot_manage_messages(): void
|
||||
{
|
||||
$this->getJson('/api/admin/messages')->assertUnauthorized();
|
||||
|
||||
$this->deleteJson('/api/admin/messages/1')->assertUnauthorized();
|
||||
|
||||
$this->patchJson('/api/admin/messages/1', ['read' => true])->assertUnauthorized();
|
||||
}
|
||||
|
||||
public function test_admins_can_list_messages(): void
|
||||
{
|
||||
$message = \App\Models\ContactMessage::create([
|
||||
'name' => 'Ali',
|
||||
'email' => 'ali@example.com',
|
||||
'message' => 'سلام',
|
||||
]);
|
||||
|
||||
Sanctum::actingAs(User::factory()->create(['is_admin' => true]));
|
||||
|
||||
$this->getJson('/api/admin/messages')
|
||||
->assertOk()
|
||||
->assertJsonPath('data.0.id', $message->id)
|
||||
->assertJsonCount(1, 'data');
|
||||
|
||||
$this->assertFalse($message->fresh()->isRead());
|
||||
}
|
||||
|
||||
public function test_admins_can_mark_a_message_as_read_and_unread(): void
|
||||
{
|
||||
$message = \App\Models\ContactMessage::create([
|
||||
'name' => 'Ali',
|
||||
'email' => 'ali@example.com',
|
||||
'message' => 'سلام',
|
||||
]);
|
||||
|
||||
Sanctum::actingAs(User::factory()->create(['is_admin' => true]));
|
||||
|
||||
$this->patchJson('/api/admin/messages/'.$message->id, ['read' => true])
|
||||
->assertOk();
|
||||
|
||||
$this->assertTrue($message->fresh()->isRead());
|
||||
|
||||
$this->patchJson('/api/admin/messages/'.$message->id, ['read' => false])
|
||||
->assertOk();
|
||||
|
||||
$this->assertFalse($message->fresh()->isRead());
|
||||
}
|
||||
|
||||
public function test_admins_can_delete_a_message(): void
|
||||
{
|
||||
$message = \App\Models\ContactMessage::create([
|
||||
'name' => 'Ali',
|
||||
'email' => 'ali@example.com',
|
||||
'message' => 'سلام',
|
||||
]);
|
||||
|
||||
Sanctum::actingAs(User::factory()->create(['is_admin' => true]));
|
||||
|
||||
$this->deleteJson('/api/admin/messages/'.$message->id)->assertOk();
|
||||
|
||||
$this->assertDatabaseMissing('contact_messages', ['id' => $message->id]);
|
||||
}
|
||||
|
||||
public function test_non_admin_users_cannot_manage_messages(): void
|
||||
{
|
||||
$message = \App\Models\ContactMessage::create([
|
||||
'name' => 'Ali',
|
||||
'email' => 'ali@example.com',
|
||||
'message' => 'سلام',
|
||||
]);
|
||||
|
||||
Sanctum::actingAs(User::factory()->create(['is_admin' => false]));
|
||||
|
||||
$this->getJson('/api/admin/messages')->assertForbidden();
|
||||
$this->patchJson('/api/admin/messages/'.$message->id, ['read' => true])->assertForbidden();
|
||||
$this->deleteJson('/api/admin/messages/'.$message->id)->assertForbidden();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user