Javascript,Nodejs,MongodDB,WordPress,CSS,PHP

LightBlog

Wednesday, January 9, 2019

How to use pagination with raw query in laravel

    public function filter(Request $request)
    {
       
        $keySearch = $request->post_text;
        $distance = 10000;
        $latitude     = $request->latitude;
        $longitude    = $request->longitude;

        $data = Post::selectRaw(DB::raw('id,user_id,post_text,post_image,color,created_at,updated_at, ( 6367 * acos( cos( radians('.$latitude.') ) * cos( radians( latitude ) ) * cos( radians( longitude ) - radians('.$longitude.') ) + sin( radians('.$latitude.') ) * sin( radians( latitude ) ) ) ) AS distance'))->where('post_text', 'LIKE', '%' .$keySearch. '%')
        ->having('distance', '<', $distance)
        ->orderBy('distance')
        ->get()->toArray();

        $raw_query =$this->paginateArray( $data );
         return $raw_query;
      
    }

    public function paginateArray($data, $perPage = 3)
    {
        $page = Paginator::resolveCurrentPage();
        $total = count($data);
       
        $results = array_slice($data, ($page-1) * $perPage, $perPage);

        return new LengthAwarePaginator($results, $total, $perPage, $page, [
            'path' => Paginator::resolveCurrentPath(),
        ]);
    }

No comments:

Post a Comment