git commit "add favorites display with polymorphic relation"

This commit is contained in:
2026-08-17 14:14:55 +03:30
parent 902384625b
commit ea1a0cc0c4
6 changed files with 61 additions and 73 deletions
+8 -14
View File
@@ -9,30 +9,24 @@ class FavoriteController extends Controller
{
public function index()
{
$favorites=Favorite::with('tour')
->where('user_id',auth()->id())
$favorites = Favorite::with('favoritable')
->where('user_id', auth()->id())
->latest()
->get();
return view('account.users.favorite.index',compact('favorites'));
return view('account.users.favorite.index', compact('favorites'));
}
public function store(Request $request)
{
$request->validate([
'tour_id'=>[
'required',
'exists:tours,id'
],
]);
Favorite::firstOrCreate([
'user_id' => auth()->id(),
'tour_id' => $request->tour_id,
'favoritable_type' => $request->type,
'favoritable_id' => $request->id,
]);
return back()->with(
'success',
'تور به علاقه‌مندی‌ها اضافه شد.'
);
return back();
}
+8 -3
View File
@@ -7,17 +7,17 @@
namespace App\Models;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Model;
/**
* Class Favorite
*
*
* @property int $id
* @property int $user_id
* @property string $favoritable_type
* @property int $favoritable_id
* @property Carbon|null $created_at
*
*
* @property User $user
*
* @package App\Models
@@ -43,4 +43,9 @@ class Favorite extends Model
{
return $this->belongsTo(User::class);
}
public function favoritable()
{
return $this->morphTo();
}
}
+4
View File
@@ -72,6 +72,10 @@ class Flight extends Model
{
return $this->hasMany(Comment::class);
}
public function favorites()
{
return $this->morphMany(Favorite::class, 'favoritable');
}
#[Scope]
public function applySearch(Builder $query, array $filters): void
+4
View File
@@ -62,4 +62,8 @@ class Tour extends Model
{
return $this->belongsTo(TravelType::class);
}
public function favorites()
{
return $this->morphMany(Favorite::class, 'favoritable');
}
}