feat: add favorites feature (model, controller, routes, view)
This commit is contained in:
@@ -0,0 +1,74 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Models\Favorite;
|
||||
use App\Models\Flight;
|
||||
use App\Models\Tour;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
class FavoriteController extends Controller
|
||||
{
|
||||
//
|
||||
public function index()
|
||||
{
|
||||
$favorites = auth()->user()->favorites()->with('favoritable')->get();
|
||||
|
||||
$items = $favorites->map(function ($favorite) {
|
||||
$item = $favorite->favoritable;
|
||||
|
||||
|
||||
|
||||
if ($item instanceof Flight) {
|
||||
return [
|
||||
'favorite_id' => $favorite->id,
|
||||
'type' => 'flight',
|
||||
'title' => 'پرواز ' . $item->flight_number,
|
||||
'subtitle' => ($item->originAirport->city ?? '') . ' به ' . ($item->destinationAirport->city ?? ''),
|
||||
'price' => number_format($item->price) . ' تومان',
|
||||
'favoritable_id' => $item->id,
|
||||
'favoritable_type' => 'flight',
|
||||
];
|
||||
}
|
||||
|
||||
if ($item instanceof Tour) {
|
||||
return [
|
||||
'favorite_id' => $favorite->id,
|
||||
'type' => 'tour',
|
||||
'title' => $item->title,
|
||||
'subtitle' => $item->summary,
|
||||
'price' => null,
|
||||
'favoritable_id' => $item->id,
|
||||
'favoritable_type' => 'tour',
|
||||
];
|
||||
}
|
||||
|
||||
return null;
|
||||
})->filter()->values(); // حذف nullها و ریایندکس
|
||||
|
||||
return view('favorites.index', compact('items' , 'favorites'));
|
||||
}
|
||||
public function toggle($type , $id)
|
||||
{
|
||||
|
||||
|
||||
$modelClass = $type === 'flight' ? Flight::class : Tour::class;
|
||||
|
||||
$favorite = Favorite::where('user_id', auth()->id())
|
||||
->where('favoritable_id', $id)
|
||||
->where('favoritable_type', $modelClass)
|
||||
->first();
|
||||
|
||||
if ($favorite) {
|
||||
$favorite->delete();
|
||||
} else {
|
||||
Favorite::create([
|
||||
'user_id' => auth()->id(),
|
||||
'favoritable_id' => $id,
|
||||
'favoritable_type' => $modelClass,
|
||||
]);
|
||||
}
|
||||
|
||||
return back();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user