Files

50 lines
1.3 KiB
PHP
Raw Permalink Normal View History

<?php
namespace App\Http\Controllers;
use App\Models\User;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Str;
class FollowController extends Controller
{
public function store(User $user): JsonResponse
{
$me = auth()->user();
if ($me->id === $user->id) {
return response()->json(['error' => 'Cannot follow yourself'], 422);
}
if (!$me->following()->where('following_id', $user->id)->exists()) {
$me->following()->attach($user->id);
$user->notifications()->create([
'id' => Str::uuid(),
'type' => 'new_follower',
'data' => json_encode([
'follower_id' => $me->id,
2026-05-30 23:47:32 +03:00
'follower_slug' => $me->slug,
'follower_name' => $me->name,
]),
'created_at' => now(),
]);
}
return response()->json([
'following' => true,
'count' => $user->followers()->count(),
]);
}
public function destroy(User $user): JsonResponse
{
auth()->user()->following()->detach($user->id);
return response()->json([
'following' => false,
'count' => $user->followers()->count(),
]);
}
}