Search code examples
laraveloopreusabilitycode-reuse

Reuse Codes In Laravel


I've some

if() {

} else {

}

condition, which is used in several times. I want to reuse them rather typing them over and over again.

here is my controller source code: MyController.php


Solution

  • You can simply put this snippet into a function say buildExamData:

    protected function buildExamData($examdata) {
        $examIdsNesting = [];
    
        foreach ($examdata as $examdatum) {
           $examIdsNesting[] = array(
              'Exam Name' => $examdatum->Name,
              'Exam Code' => $examdatum->ExamCode,
              'Exam Details' => $examdatum->Details,
              'Exam Owner' => $examdatum->Owner,
           );
        }
        return $examIdsNesting;
    }
    

    Then each time you want to perform this action just call buildExamData() eg.:

    public function GetListOfExams(Request $request)
    {
        //select Name, ExamCode,Details, Owner, from exams where owner = Owner and status = 1;
        $owner = $request->get('owner'); //get this from GET request
        $status = 1; //it is intialized here
        $examdata = Exam::select('Name', 'ExamCode', 'Details', 'Owner')->where(
            array(
                'Owner' =>  $owner,
                'status'=>  $status
            )
        )->get();
    
        return $examdata->isEmpty()
            ? response()->json('Exam not found for this Owner', 404)
            : response()->json($this->buildExamData($examdata), 200);
     }
    

    Please note that I have made a little refactor to the buildExamData() function so you don't need array_push()

    Ps: if you don't want to expose your source code I can delete the portion of the code and just leave the explanations