Laravel API - Display all districts when state field is empty

Viewed 82

Below given is my code to display the specific districts of an inputted state. But in this code itself, i want to display all districts in the db if the state field is empty. How to modify my code to get such an output. So, my desired API works such that it returns all the districts when the api is called. And only if the state field is inputted, it shows the particular districts specific to it. Help me with ur suggestions.

public function state_lookup(Request $request)
{
     $validator = Validator::make
    ($request->all(),
        [
            'state'     => 'string',
        ]
    );

    if ($validator->fails()) {
        return response()->json(
            [$validator->errors()],
            422
        );
    }

    if(empty($request->state)){
        $dist=PersonalDetails::get(['district']);
        return response()->json($dist);
    }

    $data = PersonalDetails::where('state',$request->state)->get(['district']);
 // dd($data);
    if(count($data)){

        return response()->json(['message'=>'success','data'=>$data]);
    }
    else{
        return response()->json(['message'=>'Invalid State']);
    }
}

in failure case,I am getting json result as below

    {
    "message": "success",
    "data": []
}

it shows "success" instead of "invalid state"

2 Answers

You can use when

$data = PersonalDetails::when(!empty($request->state),function ($query)use($request){
        $query->where('state',$request->state);
    })->get(['district']);

or

   $data = PersonalDetails::where(function ($query)use($request){
        if(isset($request)&&!empty($request)){
            $query->where('state',$request->state);
        }
       
    })->get(['district']);

To avoid 0 key in response change like below

if(count($data)){

   return response()->json(['message'=>'success','data'=>$data]);
} 

Try with this,

//In your controller
$request->validate([
   'state' => 'string'
]);

// $request->validate it self return error messages you have to display 
// for an example (write below code in your blade file)
@error('state')
  <div class="alert alert-danger">{{ $message }}</div>
@enderror

// write below code in your controller file
 $details = PersonalDetails::select('district');

 $details->where(function($query) use($request) {
       if (isset($request->state) && $request->state != '') {
          $query->where('state', $request->state);
       }
       // do what you want to filter in your query like above
 });

 $data = $details->get();
Related