source: app/Http/Controllers/PeopleController.php

main
Last change on this file was 3c89e27, checked in by bube-ristovska <ristovska725@…>, 4 months ago

Refactored duplicate code

  • Property mode set to 100644
File size: 2.8 KB
Line 
1<?php
2
3namespace App\Http\Controllers;
4
5use Illuminate\Http\Request;
6use Illuminate\Support\Facades\DB;
7use Illuminate\Support\Facades\Session;
8
9class PeopleController extends Controller
10{
11 function filter(){
12 if(Session::get('pe_id') == null) {
13 return view('login');
14 }
15 $peoples = DB::table('people')->get();
16 return view('filter', [
17 'peoples' => $peoples
18 ]);
19 }
20 function filter_post(){
21 if(Session::get('pe_id') == null) {
22 return view('login');
23 }
24// $credentials = request()->validate([
25// 'embg' => 'required'
26// ]);
27// $embg = $credentials['embg'];
28//
29// $peoples = DB::select('SELECT * FROM people WHERE embg ~ :embg', ['embg' => '^' . $embg]);
30
31 $credentials = request()->validate([
32 'embg' => 'nullable', // Assuming embg is not always required
33 'gender' => 'nullable',
34 'age' => 'nullable',
35 ]);
36 $query = 'SELECT * FROM people WHERE true';
37
38 $embg = '^' . $credentials['embg'];
39 if ($credentials['embg']) {
40 $query .= " AND embg LIKE '{$credentials['embg']}%'";
41 }
42
43 // Check if $credentials['gender'] is an array and handle accordingly
44 if (isset($credentials['gender']) && (is_array($credentials['gender']) && count($credentials['gender']) > 0)) {
45 $genderConditions = implode(" OR ", array_map(function ($gender) {
46 return "gender = '{$gender}'";
47 }, $credentials['gender']));
48
49 $query .= " AND ({$genderConditions})";
50 } elseif (isset($credentials['gender']) && !is_array($credentials['gender'])) {
51 $query .= " AND gender = '{$credentials['gender']}'";
52 }
53
54 // Check if $credentials['age'] is an array and handle accordingly
55 if (isset($credentials['age']) && is_array($credentials['age']) && count($credentials['age']) > 0) {
56 $ageConditions = [];
57
58 foreach ($credentials['age'] as $ageRange) {
59 // Extract minimum and maximum ages from the range
60 list($minAge, $maxAge) = explode('-', $ageRange);
61
62 // Add condition for the age range
63 $ageConditions[] = "EXTRACT(YEAR FROM AGE(current_date, date_of_birth)) BETWEEN {$minAge} AND {$maxAge}";
64 }
65
66 $query .= " AND (" . implode(" OR ", $ageConditions) . ")";
67 }
68 // Use a raw SQL query with the built conditions
69
70 $peoples = DB::select($query);
71 return view('filter', ['peoples' => $peoples]);
72 }
73 public function getPerson(Request $request)
74 {
75 $embg = $request->input('embg');
76 $person = DB::table('people')
77 ->where('embg', $embg)->get();
78 return response()->json($person[0] ?? null);
79 }
80}
Note: See TracBrowser for help on using the repository browser.