PHP code example of aybimyazilim / laravel-expo-notifications
1. Go to this page and download the library: Download aybimyazilim/laravel-expo-notifications library . Choose the download type require .
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
aybimyazilim / laravel-expo-notifications example snippets
namespace App\Notifications;
use AybimYazilim\LaravelExpoNotifications\Notifications\ExpoNotification;
class NewMessageNotification extends ExpoNotification
{
protected $message;
public function __construct($message)
{
parent::__construct();
$this->message = $message;
}
public function toExpo($notifiable): array
{
return [
'title' => 'Yeni Mesajınız Var! 💬',
'body' => "Gönderen: {$this->message->sender->name}",
'data' => [
'type' => 'message',
'message_id' => $this->message->id,
'sender_id' => $this->message->sender_id,
'action' => 'open_chat',
],
'sound' => 'default',
'priority' => 'high',
'channelId' => 'messages',
];
}
}
namespace App\Models;
use Illuminate\Foundation\Auth\User as Authenticatable;
use AybimYazilim\LaravelExpoNotifications\Models\ExpoNotificationLog;
class User extends Authenticatable
{
// Expo token için routing
public function routeNotificationForExpo()
{
return $this->expo_push_token;
}
// Notification geçmişi
public function expoNotifications()
{
return $this->morphMany(ExpoNotificationLog::class, 'notifiable');
}
// Son notification'ları al
public function recentNotifications($limit = 10)
{
return $this->expoNotifications()
->latest()
->limit($limit)
->get();
}
}
use App\Notifications\NewMessageNotification;
use Illuminate\Support\Facades\Notification;
// Kullanıcıya gönder
$user = User::find(1);
$user->notify(new NewMessageNotification($message));
// Birden fazla kullanıcıya gönder
$users = User::whereNotNull('expo_push_token')->get();
Notification::send($users, new NewMessageNotification($message));
// Belirli bir token'a gönder
Notification::route('expo', 'ExponentPushToken[xxxxxxxxxxxxxxxxxxxxxx]')
->notify(new NewMessageNotification($message));
// Bulk gönderim
$tokens = ['token1', 'token2', 'token3'];
foreach ($tokens as $token) {
Notification::route('expo', $token)
->notify(new NewMessageNotification($message));
}
use AybimYazilim\LaravelExpoNotifications\Exceptions\ExpoNotificationException;
use AybimYazilim\LaravelExpoNotifications\Exceptions\InvalidTokenException;
try {
$user->notify(new NewMessageNotification($message));
} catch (InvalidTokenException $e) {
Log::error('Geçersiz Expo token: ' . $e->getMessage());
// Token'ı temizle veya güncelle
$user->update(['expo_push_token' => null]);
} catch (ExpoNotificationException $e) {
Log::error('Expo notification hatası: ' . $e->getMessage());
}
use AybimYazilim\LaravelExpoNotifications\Services\ExpoLogService;
$logService = new ExpoLogService();
// Son 24 saatin istatistikleri
$stats = $logService->getStats('24h');
/*
[
'total' => 250,
'sent' => 240,
'failed' => 10,
'pending' => 0,
'success_rate' => 96.0,
'period' => '24h'
]
*/
// Başarısız notification'ları al
$failedNotifications = $logService->getFailedNotifications(50);
// En çok kullanılan notification türleri
$topTypes = $logService->getTopNotificationTypes(10, '30d');
// Günlük istatistikler (son 30 gün)
$dailyStats = $logService->getDailyStats(30);
// Hata analizi
$errorAnalysis = $logService->getErrorAnalysis('7d');
// routes/api.php
Route::middleware('auth:sanctum')->group(function () {
Route::post('/user/expo-token', [UserController::class, 'updateExpoToken']);
Route::get('/notifications/history', [NotificationController::class, 'history']);
Route::post('/notifications/mark-as-read', [NotificationController::class, 'markAsRead']);
});
// app/Http/Controllers/UserController.php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
class UserController extends Controller
{
public function updateExpoToken(Request $request): JsonResponse
{
$request->validate([
'expo_push_token' => 'class NotificationController extends Controller
{
protected $expoLogService;
public function __construct(ExpoLogService $expoLogService)
{
$this->expoLogService = $expoLogService;
}
public function history(Request $request): JsonResponse
{
$user = $request->user();
$history = $this->expoLogService->getUserNotificationHistory(
get_class($user),
$user->id,
$request->get('limit', 50)
);
return response()->json([
'success' => true,
'data' => $history,
]);
}
public function markAsRead(Request $request): JsonResponse
{
$request->validate([
'notification_ids' => '
use AybimYazilim\LaravelExpoNotifications\Services\ExpoService;
$expoService = app(ExpoService::class);
$messages = [
[
'to' => 'ExponentPushToken[token1]',
'title' => 'Title 1',
'body' => 'Body 1',
],
[
'to' => 'ExponentPushToken[token2]',
'title' => 'Title 2',
'body' => 'Body 2',
],
// ... daha fazla mesaj
];
$response = $expoService->sendBulkNotifications($messages);
namespace App\Exceptions;
use AybimYazilim\LaravelExpoNotifications\Exceptions\ExpoNotificationException;
class Handler extends ExceptionHandler
{
public function register()
{
$this->reportable(function (ExpoNotificationException $e) {
// Özel Expo notification hata loglama
Log::channel('expo')->error('Expo Notification Error', [
'message' => $e->getMessage(),
'context' => $e->getContext(),
'trace' => $e->getTraceAsString()
]);
// Slack, email vb. bildirim gönder
if (app()->environment('production')) {
$this->notifyAdmins($e);
}
});
}
}
use AybimYazilim\LaravelExpoNotifications\Tests\TestCase;
use Illuminate\Support\Facades\Http;
class ExpoNotificationTest extends TestCase
{
/** @test */
public function it_sends_expo_notification_successfully()
{
Http::fake([
'exp.host/--/api/v2/push/send' => Http::response([
'data' => [
[
'status' => 'ok',
'id' => 'test-ticket-id'
]
]
])
]);
$user = User::factory()->create([
'expo_push_token' => 'ExponentPushToken[test-token]'
]);
$user->notify(new NewMessageNotification($message));
Http::assertSent(function ($request) {
return str_contains($request->url(), 'exp.host') &&
$request['title'] === 'Yeni Mesajınız Var! 💬';
});
$this->assertDatabaseHas('expo_notification_logs', [
'expo_token' => 'ExponentPushToken[test-token]',
'status' => 'sent'
]);
}
/** @test */
public function it_handles_invalid_token_error()
{
Http::fake([
'exp.host/--/api/v2/push/send' => Http::response([
'data' => [
[
'status' => 'error',
'message' => 'DeviceNotRegistered',
'details' => [
'error' => 'DeviceNotRegistered'
]
]
]
])
]);
$this->expectException(InvalidTokenException::class);
$user = User::factory()->create([
'expo_push_token' => 'invalid-token'
]);
$user->notify(new NewMessageNotification($message));
}
}
bash
php artisan vendor:publish --tag=expo-notifications-config
bash
php artisan vendor:publish --tag=expo-notifications-migrations
php artisan migrate
bash
# Notification istatistiklerini görüntüle
php artisan expo:stats 24h
php artisan expo:stats 7d
php artisan expo:stats 30d
# Test notification gönder
php artisan expo:test-notification "ExponentPushToken[xxx]" "Test Title" "Test Body"
javascript
import * as Notifications from 'expo-notifications';
// Badge sayısını ayarla
async function setBadgeCount(count) {
await Notifications.setBadgeCountAsync(count);
}
// Badge sayısını temizle
async function clearBadge() {
await Notifications.setBadgeCountAsync(0);
}
// Uygulama açıldığında badge'i temizle
useEffect(() => {
const subscription = AppState.addEventListener('change', (nextAppState) => {
if (nextAppState === 'active') {
clearBadge();
}
});
return () => subscription?.remove();
}, []);