50 lines
1.3 KiB
PHP
50 lines
1.3 KiB
PHP
<?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,
|
|
'follower_username' => $me->username,
|
|
'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(),
|
|
]);
|
|
}
|
|
}
|