67 lines
2.0 KiB
PHP
67 lines
2.0 KiB
PHP
<?php
|
|
|
|
namespace App\Http\Controllers;
|
|
|
|
use App\Enums\InteractionType;
|
|
use App\Models\Deal;
|
|
use App\Models\Interaction;
|
|
use Illuminate\Support\Facades\Auth;
|
|
use Illuminate\Support\Facades\Log;
|
|
|
|
class InteractionController extends Controller
|
|
{
|
|
/**
|
|
* Interact to a deal by Like or Favorite state
|
|
*
|
|
* @param InteractionType $type [InteractionType::Like, InteractionType::Favorite]
|
|
* @return \Illuminate\Http\JsonResponse
|
|
*/
|
|
public function togglesState(Deal $deal, InteractionType $type)
|
|
{
|
|
if (! in_array($type, [InteractionType::Like, InteractionType::Favorite])) {
|
|
return response()->json(['error' => 'This interaction is not supported'], 400);
|
|
}
|
|
|
|
try {
|
|
// Check for existing like of the user with deal
|
|
$existingInteraction = $deal->interactions()
|
|
->where('user_id', Auth::id())
|
|
->where('type', $type)
|
|
->first();
|
|
|
|
// Delete the existing like if exists, else add the like
|
|
$message = '';
|
|
if ($existingInteraction) {
|
|
$existingInteraction->delete();
|
|
$message = "{$type->value} removed from deal";
|
|
} else {
|
|
$data = [
|
|
'type' => $type,
|
|
'user_id' => Auth::id(),
|
|
];
|
|
|
|
Interaction::unguard();
|
|
$deal->interactions()->create($data);
|
|
Interaction::reguard();
|
|
|
|
$message = "{$type->value} added to deal";
|
|
}
|
|
|
|
return response()->json(['message' => $message]);
|
|
|
|
} catch (\Throwable $e) {
|
|
Log::error('Error when liked a deal',
|
|
[
|
|
'deal_id' => $deal->id,
|
|
'use_id' => Auth::id(),
|
|
'type' => $type,
|
|
'error' => $e->getMessage(),
|
|
'trace' => $e->getTraceAsString(),
|
|
]
|
|
);
|
|
|
|
return response()->json(['error' => 'Something went wrong.'], 500);
|
|
}
|
|
}
|
|
}
|