CompareController.php 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. <?php
  2. namespace App\Http\Controllers;
  3. use Illuminate\Http\Request;
  4. use App\Models\Category;
  5. class CompareController extends Controller
  6. {
  7. public function index(Request $request)
  8. {
  9. //dd($request->session()->get('compare'));
  10. $categories = Category::all();
  11. return view('frontend.view_compare', compact('categories'));
  12. }
  13. //clears the session data for compare
  14. public function reset(Request $request)
  15. {
  16. $request->session()->forget('compare');
  17. return back();
  18. }
  19. //store comparing products ids in session
  20. public function addToCompare(Request $request)
  21. {
  22. if($request->session()->has('compare')){
  23. $compare = $request->session()->get('compare', collect([]));
  24. if(!$compare->contains($request->id)){
  25. if(count($compare) == 3){
  26. $compare->forget(0);
  27. $compare->push($request->id);
  28. }
  29. else{
  30. $compare->push($request->id);
  31. }
  32. }
  33. }
  34. else{
  35. $compare = collect([$request->id]);
  36. $request->session()->put('compare', $compare);
  37. }
  38. return view('frontend.partials.compare');
  39. }
  40. }