70 lines
2.3 KiB
PHP
70 lines
2.3 KiB
PHP
<?php
|
|
|
|
namespace App\Http\Controllers\Api;
|
|
|
|
use App\Http\Controllers\Controller;
|
|
use App\Models\NewsletterSubscription;
|
|
use Illuminate\Http\JsonResponse;
|
|
use Illuminate\Http\Request;
|
|
|
|
/**
|
|
* @OA\Tag(name="Newsletter", description="Blog newsletter subscriptions")
|
|
*/
|
|
class NewsletterSubscriptionController extends Controller
|
|
{
|
|
/**
|
|
* Store a new subscription. The site has no mail service of its own, so
|
|
* subscriptions are stored in the database and read from the admin panel,
|
|
* like contact messages and blog comments.
|
|
*
|
|
* A visitor may join with an email, a mobile number, or both; repeating an
|
|
* email is harmless and idempotent.
|
|
*/
|
|
public function subscribe(Request $request): JsonResponse
|
|
{
|
|
$validated = $request->validate([
|
|
'email' => ['nullable', 'email', 'max:255'],
|
|
'mobile' => ['nullable', 'string', 'max:30'],
|
|
]);
|
|
|
|
$email = isset($validated['email']) ? trim($validated['email']) : null;
|
|
$mobile = isset($validated['mobile']) ? trim($validated['mobile']) : null;
|
|
|
|
if ($email === null || $email === '') {
|
|
$email = null;
|
|
}
|
|
if ($mobile === null || $mobile === '') {
|
|
$mobile = null;
|
|
}
|
|
|
|
if ($email === null && $mobile === null) {
|
|
return response()->json([
|
|
'message' => 'حداقل ایمیل یا شماره موبایل را وارد کنید.',
|
|
'errors' => [
|
|
'email' => ['حداقل ایمیل یا شماره موبایل را وارد کنید.'],
|
|
],
|
|
], 422);
|
|
}
|
|
|
|
if ($email !== null) {
|
|
$existing = NewsletterSubscription::where('email', $email)->first();
|
|
|
|
if ($existing !== null) {
|
|
return response()->json([
|
|
'message' => 'شما قبلاً در خبرنامه عضویت داشتهاید.',
|
|
'subscribed' => true,
|
|
]);
|
|
}
|
|
}
|
|
|
|
$subscription = NewsletterSubscription::create([
|
|
'email' => $email,
|
|
'mobile' => $mobile,
|
|
]);
|
|
|
|
return response()->json([
|
|
'message' => 'عضویت شما در خبرنامه با موفقیت ثبت شد.',
|
|
'subscription' => $subscription,
|
|
], 201);
|
|
}
|
|
} |