Search code examples
laravellaravel-5laravel-5.3

Issue in laravel database query?


I am trying to run query which will fetch data between the given dates but i am not getting a desired result. I have an blank array as an output.

this is my code in controller:

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use DB;
use \Carbon\Carbon;

class reportController extends Controller
{
    public $response;

public function contact_report(Request $request){
    if($request->header('content-type')=='application/json'){
        $from = \Carbon\Carbon::parse($request->from)->format('Y-m-d');
        $to = \Carbon\Carbon::parse($request->to)->format('Y-m-d');
        $cont_report = DB::connection('mysql_freesubs')->table('contact as c')
                        ->select("c.fname", "c.lname","c.dob", "cl.value","c.doc" )             
                        ->join("communication_link AS cl", "c.id", "=", "cl.cont_id")
                        ->join("contact_communication AS cc", "cl.coco_id", "=", "cc.id")
                        ->where("cc.type", "like","mobile%")
                        ->whereBetween("c.doc", [new Carbon($from), new Carbon($to)])
                        ->get();
        $response = $cont_report;

    }
    else
        $response =  response()->json(['data'=>[],'error'=>1,'success'=>0,'error_msg'=>'not application/json', 'message'=>'Content type should be application/json']);

    return $response;
}
}

Solution

  • Try this:

    use Carbon\Carbon;
    
    class reportController extends Controller
    {
        public $response;
    
        public function contact_report(Request $request){
            if(0 === strpos($request->headers->get('Content-Type'), 'application/json')){
    
                $from = Carbon::parse($request->from)->format('Y-m-d');
                $to   = Carbon::parse($request->to)->format('Y-m-d');
                $cont_report = DB::connection('mysql_freesubs')->table('contact as c')
                                ->select("c.fname", "c.lname","c.dob", "cl.value","c.doc" )             
                                ->join("communication_link AS cl", "c.id", "=", "cl.cont_id")
                                ->join("contact_communication AS cc", "cl.coco_id", "=", "cc.id")
                                ->where("cc.type", "like","mobile%")
                                ->whereBetween("c.doc", [$from, $to])
                                ->get();
    
                //$this->response = $cont_report;
                return response()->json(['response' => $cont_report], 200);
            }
            else {
                return response()->json([
                    'data'=> [],
                    'error'=> 1,
                    'success'=> 0,
                    'error_msg'=>'not application/json', 
                    'message'=>'Content type should be application/json'
                ], 404);        
            }
        }
    }