dealhub/app/Http/Controllers/InteractionController.php
kusowl 16c9ff3cee feat: implement user interaction system with like functionality
- Updated interaction models and relations for handling of user-deal interactions.
- Added frontend interactivity with `interaction.js` for toggling like buttons.
2026-01-15 19:09:24 +05:30

48 lines
1.3 KiB
PHP

<?php
namespace App\Http\Controllers;
use App\Enums\InteractionType;
use App\Models\Deal;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
class InteractionController extends Controller
{
public function like(Deal $deal)
{
try {
// Check for existing like of the user with deal
$user = Auth::user();
$existingLike = $deal->interactions()
->where('user_id', $user->id)
->where('type', InteractionType::Like)
->first();
// Delete the existing like if exists
if ($existingLike) {
$existingLike->delete();
return response()->json(['message' => 'Successfully unliked the post.']);
}
// Else, create a new like
$data = [
'type' => InteractionType::Like,
'user_id' => Auth::user()->id,
];
Deal::unguard();
$deal->interactions()->create($data);
Deal::reguard();
} catch (\Throwable $e) {
Log::error('Error when liked a deal: id'.$deal->id.$e->getMessage(), $e->getTrace());
return response()->json(['error' => 'Something went wrong.'], 500);
}
return response()->json(['message' => 'Successfully liked the post.']);
}
}