brian85
150
5
Laravel

Best way to avoid repeating code in controler

Posted 1 month ago by brian85

Hello, I would have an advice in order to avoid repeating code in my controlers. I ofently have the same method in my controlers named 'ajaxQuery' like this :

/**
     * @param Request $request
     * @return string
     */
    public function ajaxQuery(Request $request): string
    {
        $queryString = $request->input('queryString');
        $offset = $request->input('offset');
        $limit = $request->input('limit');

        // Par défaut on limite la présentation des formation à N-1, N et N+1
        if($queryString ==''){
            $usersData = Formation::where('ref_formation','like', '%'.date('y').'S')
                ->orWhere('ref_formation','like', '%'.(date('y')+1).'S')
                ->orWhere('ref_formation','like', '%'.(date('y')-1).'S')
                ->when($limit > 0 || $offset > 0, function ($usersData) use ($limit, $offset) {
                    $usersData->take($limit)->skip($offset);
                })->get();

            $usersDatas['count'] = Formation::where('ref_formation','like', '%'.date('y').'S')
                ->orWhere('ref_formation','like', '%'.(date('y')+1).'S')
                ->orWhere('ref_formation','like', '%'.(date('y')-1).'S')
                ->get()->count();

        }else{

            $usersData = Formation::where('ref_formation', 'like', $queryString . '%')
                ->orWhere('titre', 'like', '%'.$queryString . '%')
                ->when($limit > 0 || $offset > 0, function ($usersData) use ($limit, $offset) {
                    $usersData->take($limit)->skip($offset);
                })->get();

            $usersDatas['count'] = Formation::where('ref_formation', 'like', $queryString . '%')
                ->orWhere('titre', 'like', $queryString . '%')
                ->get()->count();


        }


        $usersDatas['data'] = $usersData;

        /*$usersDatas['count'] = $usersData = Formation::where('ref_formation', 'like', $queryString . '%')
            ->where('ref_formation','like', '%'.date('y').'S')
            ->orWhere('titre', 'like', $queryString . '%')
            //->orWhere('username', 'like', $queryString . '%')
            ->get()->count();*/

        $usersDatas = json_encode($usersDatas);

        return $usersDatas;

    }

Should I create a serviceProvider ? Another solution ? Thanks for your help

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

Reply to

Use Markdown with GitHub-flavored code blocks.