Rymercyble
5 months ago

using logic in controllers

Posted 5 months ago by Rymercyble

Hello, I would be very happy if someone turns me to the right way. At the moment I'm using controllers probably in the wrong way (I'm quite not sure) When I need for example manage articles I'm using 1 controller for /articles (get,post) - list of all or filtered articles /article (get,post) - showing 1 whole specific article and often even more than 4 methods. Is that ok or should I divide it ? Also, I'm probably putting too much logic to my methods for example

public function people()
    {
        $search = Request::has('search') ? Request::get('search') : 0;
        if ($search) {
            if (Request::get('min_age') == ''){
                $min_age = '10';
            } else {
                $min_age = Request::get('min_age');
            }
            if (Request::get('max_age') == ''){
                $max_age = '120';
            } else {
                $max_age = Request::get('max_age');
            }

            $carbon = Carbon::today();
            $carbon_max = Carbon::today();
            $max_age += 1;
            $year_min = $carbon->year - $min_age;
            $year_max = $carbon_max->year - $max_age;
            $carbon_min = $carbon->setDate($year_min, $carbon->month, $carbon->day)->toDateString();
            $carbon_max = $carbon_max->setDate($year_max, $carbon->month, $carbon->day)->toDateString();

            $users = User::when(!empty(Request::get('country')),function ($query){
                $query->where('country', Country::where('name', Request::get('country'))->select('id')->first()->id);
            })->when(!empty(Request::get('physical_gender')),function ($query){
                $query->where('physical_gender', Physical_gender::where('name', Request::get('physical_gender'))->select('id')->first()->id);
            })->when(!empty(Request::get('language')),function ($query){
                $query->whereHas('languages', function($query){
                    $query->where('name', Request::get('language'));
                });
            })->when(!empty(Request::get('language_want')),function ($query){
                $query->whereHas('unknownLanguages', function($query){
                    $query->where('name', Request::get('language_want'));
                });
            })->whereBetween('date_of_birth', [$carbon_max, $carbon_min])
                ->select('nick_name','first_name','last_name','date_of_birth','hidden_id')
                ->get();
        } else {
            $users = Sentinel::getUserRepository()->select('nick_name','first_name','last_name','date_of_birth','hidden_id')->get();
        }

        return view('people', compact('users'));
    }

if this is wrong where i should store logic ?

Please sign in or create an account to participate in this conversation.