bhojkamal's avatar

return columns which are not empty/null for an id for laravel 8 API

Hello,

How to get the columns which are not (empty or null) for a id for an API in Laravel 8 API? Also don't need the created and updated time for that id too. The normal one which give all column including the created_at and updated_at column is.

public function show($id)
    {
        $patient = Patient::find($id);
        return response()->json($patient);
    }

I want to get only columns which have value and don't need the created and updated value too for that specific id. I hope there is a easy way to get it.

Thanks

Regards,

0 likes
17 replies
tykus's avatar

You could either create an Eloquent API Resource or override the toArray method on the Model class itself. to build the JSON representation of your Model instance.

For example,

// YourModel.php
public function toArray()
{
	return collect($this->getAttributes())->except(['created_at', 'updated_at'])->filter();
}

However, I don't like that idea of an inconsistent API - different requests for the same type of resource will have different keys.

bhojkamal's avatar

This is the data I get, In most case, like if no, I don't need the yes option value to update. So, the yes value option value has null, and laravel does not save the value if it has null, I am using vue to for the patient record system.

Data: { "id": 3, "created_by": 1, "screening_at": "2021-05-17", "screening_on": "Community_based", "screening_area": null, "firstname": "Hari", "lastname": "Thapa", "dob": null, "age": 25, "sex": "M", "married": "", "phone1": null, "phone2": null, "address": "Thada", "geo_location": "Native", "migrated_from": null, "migrated_year": null, "house_type": "Pucca", "education": "Yes", "grade": "bba", "work": "Office", "diet": "Non-vegetarian", "fruit_veg_intake": "Once a week", "smoking": "No", "initiation_age": null, "cessation_age": null, "cigarettes_per_day": null, "smoking_type": "", "alcohol": "No", "alcol_duration": 0, "alcol_type": "", "physical_activity": "<30 min/day", "own_vehicle": "No", "vehicle_type": "", "family_member": 6, "serial_no_household": null, "family_kidney_disease": "Unknown", "family_high_bp": "Unknown", "family_diabetes": "Unknown", "family_heart_attack_stroke": "Unknown", "family_mem_death_in_5_year": "No", "death_cause": "", "death_by": null, "kidney_disease": "Unknown", "high_bp": "No", "diabetes": "Unknown", "heart_attack_stroke": "No", "present_kidney_disease": "Not Applicable", "present_high_bp": "Not Applicable", "present_diabetes": "Not Applicable", "present_heart_attack_stroke": "Not Applicable", "height": null, "weight": null, "waist_circum": null, "hip_cirum": null, "systolic": null, "diastolic": null, "pulse_rate": null, "pulse": "", "u_leukocyte": "", "u_nitrate": "", "u_glucose": "", "u_hb": "", "u_protein": "", "qty_u_albumin": null, "qty_u_creatinine": null, "qty_u_alb_creat": null, "confm_u_albumin": null, "confm_u_creatinine": null, "confm_u_alb_creat": null, "serum_creatinine": null, "fasting_glucose": null, "hba1c": null, "tot_cholesterol": null, "hdl_cholesterol": null, "triglyceride": null, "ldl_cholesterol": null, "gross_family_income": null, "diagnosis1": "", "diagnosis2": "Hypertension", "diagnosis3": "", "diagnosis4": "", "arthritis": "", "acid_peptic_disease": "No", "chronic_back_ache": "No", "stroke": "", "blindness": "", "deafness": "", "alcohol_disorder": "No", "epilepsy": "", "thyroid_disease": "No", "tb": "", "filariasis": "", "depression": "", "cancer": "No", "pvt_health_ctr_before": "No", "govt_health_facilities": "No", "any_treatments": "Home Remedy", "health_insurance": "No", "covid_19_before": "No", "family_covid_19": "No", "family_member_covid": null, "covid_outcome": "", "cronic_lung": "No", "asthma": "No", "adminted_hospital": "", "steroids_antibiotics": "", "on_medication": "", "no_years_inhaler1": null, "no_years_inhaler2": null, "copd_emphysema": "No", "diagnosed_yrs": null, "copd_medication": "", "medication_name": null, "admitted_hos_with_copd": "", "copd_admitted_at": null, "admitted_times": null, "ever_req_oral_steroids_antibiotics": "", "use_inhalers_now": "No", "which_inhaler": null, "inhaler_fqy": null, "inhaler_duration": null, "oxygen_saturation": null, "fev1": null, "fev1_predicted": null, "fvc": null, "fvc_predicted": null, "fev1_fvc_ratio": null, "cough_first_mrng_winter": "No", "cough_day_night_winter": "No", "cough_3mths_a_year": "", "bring_phlegm_form_mrng": "", "bring_phlegm_form_day_ngt": "", "bring_phlegm_like_3mth_a_year": "", "past_3yr_cough_phlegm_3wk": "", "had_more_than_one": "", "breathless_with_strenuous": "", "short_breath_on_walking_up": "No", "iam_slower_walker": "", "istop_breath": "", "iam_breathless_to_leave_house": "No", "main_fuel1": "LPG", "fuel1_yr": 10, "main_fuel2": "Gobar gas", "fuel2_yr": 10, "created_at": "2021-05-18T14:16:41.000000Z", "updated_at": "2021-05-18T14:16:41.000000Z", "main_fuel3": "", "fuel3_yr": null, "main_fuel4": "", "fuel4_yr": null }
bhojkamal's avatar

I get this error when I send the above data to database to update for a patient.

PUT http://localhost:8000/api/patients/3  500 (Internal Server Error) on console
"message": "SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'married' cannot be null (SQL: update `patients` set `married` = ?, `smoking_type` = ?, `alcol_type` = ?, ............. on network that has 500. 

The problem will be solved if I can get the data which are not null and not empty for the patient which I am not going to update. This is especially problem with enum. Because when adding new patient not a problem for same form.

marosmjartan's avatar

This is you database problem, set the "married" column as nullable, and it will works. But I still don't understand what you're trying to do. But I have the feeling that you are approaching it incorrectly. Do you want to filter all ROWS, that has some of it column null? Or you want to filter for each row its null columns?

bhojkamal's avatar

I want to filter one row only. I know the error because I have set enum even defalut "", but when retriving data back to update it calls null for all emum value which has empty value.

And There is not just one married column, there are more than 80 enum column, If I change to married and it will come next.

So, the solution for me I get columns with value for that row.

marosmjartan's avatar

In that case. You can do foreach throw every key in the data. And unset all null values. I know this is not the best solution, but it should work...

foreach($data as $key => $value) {
    if ($value == null) {
		unset($data[$key])
	}
}

tykus's avatar

That's what the filter operation I suggested earlier would achieve.

we are not seeing how the OP is updating the record - at the outset it appeared that this was a read situation... now it has become a write problem, so relevant code would be helpful.

3 likes
bhojkamal's avatar

@tykus Please give me better solution, My update in model for resource api is

public function update(Request $request, $id)
    {
        $patient = Patient::find($id);
        $patient->update($request->all());
        return response()->json('The patient successfully updated');
    }

If I send data with value only, it will update.

bhojkamal's avatar

@marosmjartan,

Still it is returning all key and value. If it work. It will be fine for me. I want to remove that key if value is null. And my issue will be solved.

tykus's avatar
tykus
Best Answer
Level 104

You can array_filter the Request payload to remove keys with empty/falsey values:

$patient->update(
	array_filter($request->all())
);

This might be a little brutal however, any real false, null, "" values will be discarded

1 like
bhojkamal's avatar

@tykus

Thank you very much. It worked. I voted the best answer too.

If you also work on vue.js Please suggest me I want to filter in vue.js 3 at the frontend the start of loading the data on form. My code in frontend on vue.js is as below.

export default {
    data() {
        return {
            patient: {},
            errors: [],
            step:1,

        }
    },
    created() {        
      this.$axios.get('/sanctum/csrf-cookie').then(response => {
            this.$axios.get(`/api/patients/${this.$route.params.id}`)
                .then(response => {
                    this.patient = response.data
                    /* .filter(function(item) {
                    item !== null;
                    }) */ // I tried to filter here but didn't work. 
                })
                .catch(function (error) {
                    console.error(error);
                });
        })
    }, 
methods: {
...
}
}
Tray2's avatar

This is the problem

$patient->update($request->all());

It overwrites everything in the current record.

If you do a proper validation for each of the fields then you will get an array of the updated values

$validData = $request->validate($rules);
$patient = Patient::findOrFaile($id);
$patient->update($validData);

https://laravel.com/docs/8.x/validation#introduction

bhojkamal's avatar

@tray2

$patient = Patient::find($id);
$patient->update($request->all());

It will update the fields which are received from frontend key=>value. So, I want to remove the key if they have value empty or null. Because out of 150 fields, 10-15% fields will be empty even if we fill all field in form as, there is option if the Yes go for more options if no, stop go next section, like that. In my patient update form, I have patient object, that is pulling everything for that row. So, I want to stop to pull empty or null value.

on Vue I have as below v-model:patient.name, like that in input field.

data() {
        return {
            patient: {},
            errors: [],
        }
    },
updatePatient() {
            this.$axios.get('/sanctum/csrf-cookie').then(response => {
                this.$axios.put(`/api/patients/${this.$route.params.id}`, this.patient)
                    .then(response => {
                        this.$router.push({name: 'patients'})
                    })
                    .catch(function (error) {
                        console.error(error);
                    });
            })
        }

I have another hospital resources, It is working perfectly as it has just 5-6 fields only,

Tray2's avatar

Because out of 150 fields, 10-15% fields will be empty

This tells me you need to think about your database model a bit.

Regarding this

"message": "SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'married' cannot be null (SQL: update `patients` set `married` = ?, `smoking_type` = ?, `alcol_type` = ?, ............. on network that has 500. 

You need to either allow the field to be null or use a default value. You can use a magic setter method as well.

Here is an example how such attribute could look

 public function setSeriesAttribute($value)
    {
        if (!isset($value)) {
            $this->attributes['series'] = 'Standalone';
        } else {
            $this->attributes['series'] = ucwords(strtolower($value));
        }
    }

Please or to participate in this conversation.