Laravel技术问询:如何通过data->postid删除数据库通知行
Delete Laravel Database Notifications by
postid in JSON data Field Got it, let's walk through how to delete those specific database notifications using the postid stored in the JSON data column. Since Laravel handles JSON fields natively in the query builder, this is straightforward once you know the right methods to use.
Method 1: Using Query Builder Directly
You can target the notifications table directly, filtering by the notifiable user, notification type (optional but recommended), and the postid inside the data JSON:
use Illuminate\Support\Facades\DB; use App\Models\User; // Define your target values $targetUserId = 48; // The user who received the notification $targetPostId = 123; // The post ID from the notification data DB::table('notifications') // Filter by the user who owns the notification ->where('notifiable_type', User::class) ->where('notifiable_id', $targetUserId) // Optional: Only target PostLiked notifications ->where('type', 'App\Notifications\PostLiked') // Match the postid inside the JSON data field ->whereJsonContains('data->postid', $targetPostId) ->delete();
Method 2: Using the User Model's Notifications Relationship
If your User model uses the Notifiable trait (which it should, since you're using database notifications), you can use the built-in notifications relationship to make the query more expressive:
use App\Models\User; $user = User::find(48); $user->notifications() ->where('type', 'App\Notifications\PostLiked') ->whereJsonContains('data->postid', 123) ->delete();
Key Notes
- Double-check the key name in your JSON data: Make sure it's exactly
postid(case-sensitive!) as shown in your example data. If it's camelCase likepostId, adjust the query todata->postId. whereJsonContainsworks in Laravel 5.5+ (which matches your version), so you don't have to worry about compatibility issues here.- If you need to delete notifications for a post across all users (not just one), simply remove the
notifiable_idandnotifiable_typeclauses from the query.
内容的提问来源于stack exchange,提问作者Saurabh Mistry
相关产品推荐
相关产品推荐

