Search code examples
phplaravelweblaravel-blade

How can I add 'if' condition in laravel pagination which I used in foreach loop?


This below code is the controller code. Where my logic is there. Want to get those profiles that have no log

    public function not_checked_yet() {
        $pageName = "Not Checked Profiles";
        $status = "Active";
        $treeView = "Clients";
        $groupbyActivation = $this->groupbyActivation();
        $adminSerchs = BbUser::select(['id', 'profile_id', 'user_profession', 'user_looking_for', 'user_profile_image', 'user_date_of_birth', 'user_religion', 'present_district', 'country_of_residence', 'activation', 'membership_status'])
                        ->where('activation', 1)
                        ->where('membership_status', 107)
                        ->where('office_id', auth()->user()->agent_id)
                        ->orderBy('created_at', 'DESC')
                        ->paginate(5);  
        return view('agent.profile.search-result.not-check-search-result', compact('adminSerchs', 'pageName', 'groupbyActivation', 'status','treeView'));

    }

This below code is the view blade code. Where I used an if condition in foreach loop. So, how can I use this if condition in my pagination also?

@foreach ($adminSerchs as $key => $search_result)
   @php
     $none_check_log = \App\AgentsRemark::where('profile_id', 
     $search_result->profile_id)->count();
   @endphp
   @if($none_check_log < 1)
     <tr class="odd gradeX">
      <td>
       {{ $search_result->name }}
      </td>
   @endif
@endforeach
  {{ $adminSerchs->links() }}


Solution

  • Update your BbUser.php model and link with hasMany relationship.

    public function agent_remarks(){
      return $this->hasMany(AgentsRemark::class,"profile_id","profile_id");
    }
    

    Now in your controller check the absence of a relationship agent_remarks using doesntHave so your query would be like below, and you don't need to use if condition in your blade file.

    $adminSerchs = BbUser::doesntHave('agent_remarks')
                        ->select(['id', 'profile_id', 'user_profession', 'user_looking_for', 'user_profile_image', 'user_date_of_birth', 'user_religion', 'present_district', 'country_of_residence', 'activation', 'membership_status'])
                        ->where('activation', 1)
                        ->where('membership_status', 107)
                        ->where('office_id', auth()->user()->agent_id)
                        ->orderBy('created_at', 'DESC')
                        ->paginate(5);
    

    checkout for the detail understading on relationships : https://laravel.com/docs/8.x/eloquent-relationships#querying-relationship-absence