Friency Fernandez
Friency Fernandez

Reputation: 445

Laravel Eloquent nullable fields value converted to string "NULL"

I have in my model a query to get data from the database and there are nullable fields present in my database table. When I try to display all the records in my view, the fields which are of null value, is displayed as "NULL". I want these values to be display as just empty string.

Here is what I have in my controller:

public function showDetails($action, $id)
{
        $data_model= new PersonData();
        $persons= $data_model->loadSpecificPerson($id);

        return view('pages.admin.reporting_person_details', ['action' => $action, 'id' => $id])->with('id', $id)->with(compact('persons'));
}

In my model:

public function loadSpecificPerson($id)
{
        $persons = DB::select("SELECT * FROM complainant_t WHERE ComplainantID = ?", [$id]);
        return $persons;
}

I wanted to do it like how you would do it in an array:

foreach($array as $key => $value)
{
   if($array[$key] == NULL)
   {
        $array[$key] = "";
   }
}

This isn't possible to use with $persons since it's an object and must be accessed with name right? So how should I perform this without having to access it by the column names?

Upvotes: 1

Views: 3748

Answers (3)

Friency Fernandez
Friency Fernandez

Reputation: 445

Since I'm not the one who made the DB, I've just realized the problem is because the field values are "NULL" (string). I've modified it to be NULL and it is working fine now without having to convert it to empty string.

Upvotes: 1

Naincy
Naincy

Reputation: 2943

Use is_null or === operator.

  • is_null($result['column'])
  • $result['column'] === NULL

In Laravel, you can read about `toArray()' that will convert object to array and later you can use normal logic. Ref: https://laravel.com/docs/5.2/collections

In Model

   return $persons->toArray();

Logic

$object = new stdClass();
foreach($array as $key => $value)
{
    $array[$key] = is_null($value) ? '' : $value;
    $object->$key = is_null($value) ? '' : $value;
}

If you want to use object then use $object variable else $array as array

Upvotes: 0

Vaibhavraj Roham
Vaibhavraj Roham

Reputation: 1165

Basically NULL field is always displayed '' empty string. But if not then you can achieve as below.

foreach($persons as $person){
    //consider you want to display here
    //Please check it's NULL or 'NULL'
    echo $person->field === NULL ? '' : $person->field;
}

Here basically it will check all fields, If field is NULL then it will display '' empty string else it will display original value.

Hope it helps you!

Upvotes: 0

Related Questions