Home » Php » php – Laravel use condition in query in result

php – Laravel use condition in query in result

Posted by: admin February 25, 2020 Leave a comment

Questions:

I using laravel as Rest API, I get data from controller:

$user= User::where('id', $id)->first(['id', 'name', 'phone', 'work', 'address']);

result:

{
  "data": {
    "id": 1,
    "name": "mike shinoda",
    "phone": "0584634425",
    "work": null,
    "address": null
  }
}

Now I want get a secret data, it’s national ID, I don’t want to include this in json data, just want to detect, if it set, return another data. I want if national id is set,

$user= User::where('id', $id)->first(['id', 'name', 'phone', 'work', 'address', 'national_id']);

result:

{
  "data": {
    "id": 1,
    "name": "mike shinoda",
    "phone": "0584634425",
    "work": null,
    "address": null,
    "national_id": 2115 // I don't want this
  }
}

Instead want if national id is set, return data like this:

{
  "data": {
    "id": 1,
    "name": "mike shinoda",
    "phone": "0584634425",
    "work": null,
    "address": null,
    "verified": true // return this if national id is set
  }
}

What I tried:

  $verified = false;
    $national = User::where('id', $id)
        ->whereNotNull('national_id')
        ->first();
    if($national){
        $verified = true;
    }
    $user= User::where('id', $id)->first(['id', 'name', 'phone', 'work', 'address']);
    $user['verified'] = $verified;

But I think it’s kinda not clean and don’t want to use two query for a simple JSON data, is there a way to do this with one query not two?

How to&Answers:

you can use DB::raw for with case like below

$user= User::select('id', 'name', 'phone', 'work', 'address', 
DB::raw("(CASE WHEN national_id > 0 THEN 'true' ELSE 'false' END)  AS verified")
)->where('id', $id)->first();

Answer:

Instead you should use resources for the response. You can controll the exact json data you return for a model.
Read more about the resources:

https://laravel.com/docs/6.x/eloquent-resources#writing-resources