No : 1 - Example Of How Not To Write Code in Laravel
Tags: php, laravel, codereview, codequality
Published: 2022-10-27 16:38:46

## Story Behind
 
Hi Guys . I am Saravana Thiyagarajan a PHP developer with 1.5years on experience. I have built some decent level of apps in Laravel.

After a Long Search joined in new organization which has a CRM & other small social networking apps . I have joined a Junior PHP developer & They assigned me a task on CRM Application And That is the reason for this post . 

## The Sample Code - 1

```
 /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        //check if the user is relational manager then show selected user data else login user data
        $this->middleware('auth');
        $this->middleware(function ($request, $next) {
            $this->login_user_id = (auth()->user()->roles->contains('slug', 'relational-manager') && auth()->user()->selected_realtor) ? auth()->user()->selected_realtor->realtor_id : auth()->user()->id;
            $this->login_user = User::where('id',$this->login_user_id)->first();

            return $next($request);
        });
    }
```
**Try to understand what is happening is constructor**

In whole application all controllers are simply copy pasted same the code was written by my Team Lead.

## Solution - 1

Just create a middleware & assign on routes file for all the enpoints 

## Example 

```
Route::group(['middleware'=>'xxxx'],function()
{
    Route::get('payments',PaymentsController::class);
    Route::get('transactions',TransactionsController::class);

});

```

---


Lets see one another function to in that same controller.
Plz forgive me . Just take a look at  the sample code. This how the whole project code is done.

**Its just for example how not to code**

## The Sample Code - 2 

```
/**
     * XXXXXXX transfer.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function XXXXXXXXXX_new(Request $request)
    { 
        if (!auth()->user()->canAccess('xxxxxxx')) {
            return response()->json([
                'status' => 'error',
                'message'=> "Permission denied"
            ]);
        }
        
        $customMessages = [
            'required' => 'The :attribute field can not be empty',
            'array' =>'The :attribute field must be array'
        ];

        $validator = Validator::make($request->all(),[
            'xxxxxxx' =>'required',
            'xxxxxx' => 'nullable|string',
            'xxxxxx' => 'nullable',
            'xxxxxx' => 'nullable|array',
            'id' => "required_if:select_all,==,false|array",
            "xxxxxxx" => 'nullable',
        ],$customMessages);

        if($validator->fails()){
            return response()->json([
                'ststus'=>'error',
                'message' =>implode(',', $validator->errors()->all())
            ]);
        }

        $to = $request->xxxxxxx;

        $transfer = [
            'status' => false,
            'lead_data' => []
        ];


        $filter_info_test = $request->xxxxxxx;
        $filter_info = json_decode($filter_info_test, true);
        if($request->filled('select_all')){
            if($request->select_all == "true"){
                if($request->uncheck){
                    if(count($request->uncheck) > 0){
                        //remove unselected leads

                        $xxxx = Lxxxx::where(function($query){
                            if(auth()->user()->hasRole('brokerage')){
                                $query->whereHas('bbbbbbbbb',function($query){
                                    $query->whereHas('rrrrrrrr',function($qu){
                                        $qu->where('sssss', 'brokerage');
                                    });
                                });
                            }
                            else{
                                $query->where('owner',$this->login_user_id)->orWhereHas('tttttt',function($query1){
                                    $query1->where('tttttt',$this->login_user_id);
                                });
                            }
                        })->whereNotIn('id',$request->uuuuuuu);
                        
                        if(!empty($infooo)){

                            if(array_key_exists('search', $infooo) == true){
                                $ls->where(function($query)use($request, $filter_info){
                                    $query->where('name', 'LIKE', '%'.$filter_info['search'] .'%');
                               
                                });
                            }
                            if(array_key_exists('phone', $filter_info) == true){
                                $leads->whereHas('nono', function($query) use($request, $filter_info) {
                                    $query->where('label', $filter_info['phone']) ;
                                });
                            }
    
                            if(array_key_exists('email', $filter) == true){
                                $leads->whereHas('email_address', function($query1) use($request, $filter_info) {
                                    $query1->where('label', $filter_info['email']);
                                });
                            }
    
                            if(array_key_exists('source', $filter_info) == true){
                                $leads->whereHas('sources',function($query) use($request, $filter_info) {
                                    $query->whereIn('id',json_decode($filter_info['source']));
                                });
                            }
    
                            if(array_key_exists('stage', $filter_info) == true){
                                $leads->whereHas('stages',function($query) use($request, $filter_info) {
                                    $query->whereIn('id',json_decode($filter_info['stage']));
                                });
                            }
    
                            if(array_key_exists('tag', $filter_info) == true){
                                $leads->whereHas('tags_leads',function($query) use($request, $filter_info) {
                                    $query->whereIn('lead_tag_id',json_decode($filter_info['tg']));
                                });
                            }
    
                            if(array_key_exists('expert', $filter_info) == true){
                                $leads->whereHas('transaction',function($query) use($request, $filter_info) {
                                    $query->whereIn('to',json_decode($filter_info['expert']));
                                })->orWhere(function($query1) use($request, $filter_info) {
                                    $query1->doesntHave('transaction')->whereIn('owner',json_decode($filter_info['expert']));
                                });
                            }
                        }
                        
                        
                        
                        $leads_id = $leads->pluck('id');
                    }
                    else{
                        //work with all leads

                        $leads = Lead::where(function($query){
                            if(auth()->user()->hasRole('brokerage')){
                                $query->whereHas('brokerage_user',function($query){
                                    $query->whereHas('roles',function($qu){
                                        $qu->where('slug', 'brokerage');
                                    });
                                });
                            }
                            else{
                                $query->where('owner',$this->login_user_id)->orWhereHas('transaction',function($query1){
                                    $query1->where('to',$this->login_user_id);
                                });
                            }
                        });

                        if(!empty($filter_info)){

                            if(array_key_exists('search', $filter_info) == true){
                                $leads->where(function($query)use($request, $filter_info){
                                    $query->where('name', 'LIKE', '%'.$filter_info['search'] .'%');
                               
                                });
                            }
                            if(array_key_exists('phone', $filter_info) == true){
                                $leads->whereHas('phone_number', function($query) use($request, $filter_info) {
                                    $query->where('label', $filter_info['phone']) ;
                                });
                            }
    
                            if(array_key_exists('email', $filter_info) == true){
                                $leads->whereHas('email_address', function($query1) use($request, $filter_info) {
                                    $query1->where('label', $filter_info['email']);
                                });
                            }
    
                            if(array_key_exists('source', $filter_info) == true){
                                $leads->whereHas('sources',function($query) use($request, $filter_info) {
                                    $query->whereIn('id',json_decode($filter_info['source']));
                                });
                            }
    
                            if(array_key_exists('stage', $filter_info) == true){
                                $leads->whereHas('stages',function($query) use($request, $filter_info) {
                                    $query->whereIn('id',json_decode($filter_info['stage']));
                                });
                            }
    
                            if(array_key_exists('tag', $filter_info) == true){
                                $leads->whereHas('tags_leads',function($query) use($request, $filter_info) {
                                    $query->whereIn('lead_tag_id',json_decode($filter_info['tg']));
                                });
                            }
    
                            if(array_key_exists('expert', $filter_info) == true){
                                $leads->whereHas('transaction',function($query) use($request, $filter_info) {
                                    $query->whereIn('to',json_decode($filter_info['expert']));
                                })->orWhere(function($query1) use($request, $filter_info) {
                                    $query1->doesntHave('transaction')->whereIn('owner',json_decode($filter_info['expert']));
                                });
                            }
                        }

                        
                        $leads_id = $leads->pluck('id');
                    }
                }else{
                    $leads = Lead::where(function($query){
                        if(auth()->user()->hasRole('brokerage')){
                            $query->whereHas('brokerage_user',function($query){
                                $query->whereHas('roles',function($qu){
                                    $qu->where('slug', 'brokerage');
                                });
                            });
                        }
                        else{
                            $query->where('owner',$this->login_user_id)->orWhereHas('transaction',function($query1){
                                $query1->where('to',$this->login_user_id);
                            });
                        }
                    });

                    if(!empty($filter_info)){

                        if(array_key_exists('search', $filter_info) == true){
                            $leads->where(function($query)use($request, $filter_info){
                                $query->where('name', 'LIKE', '%'.$filter_info['search'] .'%');
                           
                            });
                        }
                        if(array_key_exists('phone', $filter_info) == true){
                            $leads->whereHas('phone_number', function($query) use($request, $filter_info) {
                                $query->where('label', $filter_info['phone']) ;
                            });
                        }
    
                        if(array_key_exists('email', $filter_info) == true){
                            $leads->whereHas('email_address', function($query1) use($request, $filter_info) {
                                $query1->where('label', $filter_info['email']);
                            });
                        }
    
                        if(array_key_exists('source', $filter_info) == true){
                            $leads->whereHas('sources',function($query) use($request, $filter_info) {
                                $query->whereIn('id',json_decode($filter_info['source']));
                            });
                        }
    
                        if(array_key_exists('stage', $filter_info) == true){
                            $leads->whereHas('stages',function($query) use($request, $filter_info) {
                                $query->whereIn('id',json_decode($filter_info['stage']));
                            });
                        }
    
                        if(array_key_exists('tag', $filter_info) == true){
                            $leads->whereHas('tags_leads',function($query) use($request, $filter_info) {
                                $query->whereIn('lead_tag_id',json_decode($filter_info['tg']));
                            });
                        }
    
                        if(array_key_exists('expert', $filter_info) == true){
                            $leads->whereHas('transaction',function($query) use($request, $filter_info) {
                                $query->whereIn('to',json_decode($filter_info['expert']));
                            })->orWhere(function($query1) use($request, $filter_info) {
                                $query1->doesntHave('transaction')->whereIn('owner',json_decode($filter_info['expert']));
                            });
                        }
                    }
                    
                    $leads_id = $leads->pluck('id');
                }
            }
            else{
                //use old code
                $leads = Lead::where(function($query){
                    if(auth()->user()->hasRole('brokerage')){
                        $query->whereHas('brokerage_user',function($query){
                            $query->whereHas('roles',function($qu){
                                $qu->where('slug', 'brokerage');
                            });
                        });
                    }
                    else{
                        $query->where('owner',$this->login_user_id)->orWhereHas('transaction',function($query1){
                            $query1->where('to',$this->login_user_id);
                        });
                    }
                })->whereIn('id',$request->id);
                
                if(!empty($filter_info)){

                    if(array_key_exists('search', $filter_info) == true){
                        $leads->where(function($query)use($request, $filter_info){
                            $query->where('name', 'LIKE', '%'.$filter_info['search'] .'%');
                       
                        });
                    }
                    if(array_key_exists('phone', $filter_info) == true){
                        $leads->whereHas('phone_number', function($query) use($request, $filter_info) {
                            $query->where('label', $filter_info['phone']) ;
                        });
                    }
    
                    if(array_key_exists('email', $filter_info) == true){
                        $leads->whereHas('email_address', function($query1) use($request, $filter_info) {
                            $query1->where('label', $filter_info['email']);
                        });
                    }
    
                    if(array_key_exists('source', $filter_info) == true){
                        $leads->whereHas('sources',function($query) use($request, $filter_info) {
                            $query->whereIn('id',json_decode($filter_info['source']));
                        });
                    }
    
                    if(array_key_exists('stage', $filter_info) == true){
                        $leads->whereHas('stages',function($query) use($request, $filter_info) {
                            $query->whereIn('id',json_decode($filter_info['stage']));
                        });
                    }
    
                    if(array_key_exists('tag', $filter_info) == true){
                        $leads->whereHas('tags_leads',function($query) use($request, $filter_info) {
                            $query->whereIn('lead_tag_id',json_decode($filter_info['tg']));
                        });
                    }
    
                    if(array_key_exists('expert', $filter_info) == true){
                        $leads->whereHas('transaction',function($query) use($request, $filter_info) {
                            $query->whereIn('to',json_decode($filter_info['expert']));
                        })->orWhere(function($query1) use($request, $filter_info) {
                            $query1->doesntHave('transaction')->whereIn('owner',json_decode($filter_info['expert']));
                        });
                    }
                }
                
                $leads_id = $leads->pluck('id');
            }
        } else{
            //use old code
            $leads = Lead::where(function($query){
                if(auth()->user()->hasRole('brokerage')){
                    $query->whereHas('brokerage_user',function($query){
                        $query->whereHas('roles',function($qu){
                            $qu->where('slug', 'brokerage');
                        });
                    });
                }
                else{
                    $query->where('owner',$this->login_user_id)->orWhereHas('transaction',function($query1){
                        $query1->where('to',$this->login_user_id);
                    });
                }
            })->whereIn('id',$request->id);
            
            if(!empty($filter_info)){

                if(array_key_exists('search', $filter_info) == true){
                    $leads->where(function($query)use($request, $filter_info){
                        $query->where('name', 'LIKE', '%'.$filter_info['search'] .'%');
                   
                    });
                }
                if(array_key_exists('phone', $filter_info) == true){
                    $leads->whereHas('phone_number', function($query) use($request, $filter_info) {
                        $query->where('label', $filter_info['phone']) ;
                    });
                }
    
                if(array_key_exists('email', $filter_info) == true){
                    $leads->whereHas('email_address', function($query1) use($request, $filter_info) {
                        $query1->where('label', $filter_info['email']);
                    });
                }
    
                if(array_key_exists('source', $filter_info) == true){
                    $leads->whereHas('sources',function($query) use($request, $filter_info) {
                        $query->whereIn('id',json_decode($filter_info['source']));
                    });
                }
    
                if(array_key_exists('stage', $filter_info) == true){
                    $leads->whereHas('stages',function($query) use($request, $filter_info) {
                        $query->whereIn('id',json_decode($filter_info['stage']));
                    });
                }
    
                if(array_key_exists('tag', $filter_info) == true){
                    $leads->whereHas('tags_leads',function($query) use($request, $filter_info) {
                        $query->whereIn('lead_tag_id',json_decode($filter_info['tg']));
                    });
                }
    
                if(array_key_exists('expert', $filter_info) == true){
                    $leads->whereHas('transaction',function($query) use($request, $filter_info) {
                        $query->whereIn('to',json_decode($filter_info['expert']));
                    })->orWhere(function($query1) use($request, $filter_info) {
                        $query1->doesntHave('transaction')->whereIn('owner',json_decode($filter_info['expert']));
                    });
                }
            }
            
            $leads_id = $leads->pluck('id');
        }

        foreach($leads_id as $id){

            $lead = Lead::where('id',$id)->first();
            if($lead){
                $from = empty($lead->transaction) ? config('envs.super_user_id') : $lead->transaction->to;
                $leda_user = User::where('id',$lead->user_id)->first();
                if(empty($lead->transaction)||$from != $to){
    
                    $lead_transfer_data = [
                        'lead_id' => $id,
                        'from' => $from,
                        'to' => $to,
                        "assign_type" => "Manual",
                        'user_id' => auth()->user()->id,
                        "reason" => $request->reason ?? null
                    ];
                    LeadTransfer::create($lead_transfer_data);  
                                        
                    $user_from = User::where('id',$from)->first();
                    $user_to = User::where('id',$to)->first();
                    
                    if($leda_user){
                        $leda_user->update(['expert'=>$to]);

                        $transfer_data = [
                            'lead_id' => $lead->user_id,
                            'realtor_from' => $from,
                            'realtor_to' => $to,
                            'relation_manager_from' => optional($user_from->relational_manager)->relational_manager_id,
                            'relation_manager_to' => (!empty($user_to->relational_manager) && $user_to->relational_manager->permission->contains('slug', 'chat-auto-join')) ? optional($user_to->relational_manager)->relational_manager_id : null,
                        ];
    
                        $this->chatTransferCall($transfer_data);
                    }

                    //send notification
    
                    $transfer['status'] = true;
                    $transfer['lead_data'][] = $lead;
    
                    //add transaction note
                    $data22['lead_id'] = $id;
                    $data22['content'] = ucfirst(auth()->user()->name)." transferred the lead from ". $user_from->name." to ".$user_to->name .(!empty($request->reason) ? " due to ".$request->reason."." : "." );
                    $data22['user_id'] = auth()->user()->id;
                    $data22['type'] = "Automatic";
                    Note::create($data22);   
                    
                }
            }
        }

        if($transfer['status']){
            if(auth()->user()->id != $to){
                //send notification

                $details = [
                    'body' => ucfirst(auth()->user()->name).' transferred some leads',
                    'data' => $transfer['lead_data'],
                    'description' => ucfirst(auth()->user()->name).' transferred some leads',
                    'subject' => 'Lead transfer - '.ucfirst(auth()->user()->name),
                    'user' => $user_to,
                    'lead_id' => $transfer['lead_data'][0]->id,
                    'lead_name' => $transfer['lead_data'][0]->name,
                    'notificationFor' =>'Enquiry',
                    'lead_email' => $transfer['lead_data'][0]->email_address->email,
                    'lead_phone' => $transfer['lead_data'][0]->phone_number->number,
                    'lead_source'=>$transfer['lead_data'][0]->sources->name,
                    'lead_stage' =>$transfer['lead_data'][0]->stages->name
                ];

                Notification::send($user_to, new EnquiryNotification($details));
            }
        }


        return response()->json([
            'status' => 'success',
            'message' => 'Leads transferred successfully'
        ]);

    }

```

## For Solution 

---

I post it on next post according to the response for this post. 

just feel free to share your experience like this in comments section.

Just Share your thoughts on this & give a Tip for me as a Junior developer what can i do in this Situation. 

---

like share & comment