0

enter image description here

I am building an application where there is a column of data that I am serializing to store in the database because I found no other way to store the data as one object. My form where the data is input checkboxes looks like this.

    <div class="form-group form-check col-sm-6">
        </br>
        <label for="careplan">Care Plan</label></br>
        <input type ="checkbox" name="careplan[]" value="nursecallweekly">   Nurse call weekly</br>
        <input type ="checkbox" name="careplan[]" value="nursecallbiweekly">   Nurse call bi-monthly</br>
        <input type ="checkbox" name="careplan[]" value="nursecallmonthly">   Nurse call monthly</br>
        <input type ="checkbox" name="careplan[]" value="weightcheckdaily">   Weight check daily</br>
        <input type ="checkbox" name="careplan[]" value="weightcheckweekly">   Weight check weekly</br>
        <input type ="checkbox" name="careplan[]" value="lowerextremity">   Lower extremity edema status</br>
        <input type ="checkbox" name="careplan[]" value="dietaryreview">   Dietary review</br>
        <input type ="checkbox" name="careplan[]" value="fluidintake">   Fluid intake review</br>
        <input type ="checkbox" name="careplan[]" value="bloodpressure">   Blood pressure reading daily</br>
        <input type ="checkbox" name="careplan[]" value="bloodpressureweekly">   Blood pressure reading weekly</br>
        <input type ="checkbox" name="careplan[]" value="hypertensive">   Hypertensive symptoms check</br>
        <input type ="checkbox" name="careplan[]" value="ptinrweekly">   PT/INR weekly review</br>
    </div>

The care plan has multiple items that can be selected. I grouped them into an array and serialized the array using.

    //Create new Patient information
    $patient = new Patient;
    $patient->first_name = $request->input('first_name');
    $patient->last_name = $request->input('last_name');
    $patient->dob = $request->input('dob');
    $patient->contact_one = $request->input('contact_one');
    $patient->contact_two = $request->input('contact_two');
    $patient->care_giver_one = $request->input('care_giver_one');
    $patient->care_giver_two = $request->input('care_giver_two');
    $patient->enrollment_reason = $request->input('enrollment_reason');
    $care_plan = $request->input('careplan');
    $cp = serialize($care_plan);
    $patient->careplan = $cp;
    $patient->save();

The image at the top is the view. As you can see, the serialized data is returned. I have looked through this forum and none of the posted suggestions worked.

unserialize data in laravel

This page doesn't even come close to what I am trying to do.

https://laravel.com/docs/5.8/eloquent-serialization#date-serialization

This was close but did not share what was done that worked or I don't understand what worked.

https://laracasts.com/discuss/channels/laravel/problem-to-unserialize-my-returned-value

UPDATE: SOLUTION THAT WORKED FOR ME

I made a couple of changes that helped and I am 98% of the way there.

This post helped me. Split string in Laravel Framework

I changed this line from this

  $care_plan = $request->input('careplan');

To this

 $patient->careplan = json_encode($request->input('careplan'));

That got me a return from the database of this.

 ["nursecallweekly","nursecallbiweekly","nursecallmonthly"]

and I used this nested loop to parse the string.

    @foreach(explode('","', $patient->careplan) as $plan)
         <li>{{$plan = Str::after($plan,'["')}}</li>
    @endforeach

What displays like this.

   nursecallweekly
   nursecallbiweekly
   nursecallmonthly"]

My only issue now is the trailing bracket.

Solution to the trailing brace

   @foreach(explode('","', $patient->careplan) as $plan)
        @if(Str::contains($plan, '['))
        <li>{{ Str::after($plan,'["') }}</li>
        @else
            <li>{{ Str::before($plan,'"]') }}</li>
        @endif
    @endforeach
user1794918
  • 1,131
  • 2
  • 16
  • 34
  • What's wrong with [unserialize](https://www.php.net/manual/en/function.unserialize.php)? – aynber Jan 15 '20 at 16:10
  • aynber, unserialize did not work for me or couldn't figure out where to place the unserialize($patient->careplan). This would throw an error big time. So I had to go back to how the data was being stored. I change to json_encode along with the suggestion made below as the answer to cast using the mutator. When the string was brought back, that is where all these other steps were brought in to render the string. – user1794918 Jan 18 '20 at 21:20

1 Answers1

1

You should use Eloquent mutators to do this.

Use a JSON column on your database, let's call it careplan, then in your model do:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Patient extends Model
{
    // ...

    protected $casts = [
        'careplan' => 'array',
    ];

    // ...
}

So now, you will work with an array element, there isn't need to manually serialize/unserialize it from the database anymore. Laravel will convert the array to json when storing and casting it back to array when getting the value from the database. So now:

$patient = new Patient;
$patient->first_name = $request->input('first_name');
// ...
$patient->careplan = $request->input('careplan'); // Laravel will convert it to json for you
$patient->save();

Then you'll see that:

$patient = Patient::find(1);
dd($patient->careplan);

Has been casted back to array.

Kenny Horna
  • 13,485
  • 4
  • 44
  • 71
  • Thanks. what did was add first code to the apps>Http>Models>CarePlan.php. Then in the PatientController.php I wrote it as shown in the second code snippet. When I tried to save a new patient an error occurred. Array to string conversion error. I don't know what to do with the last part. Where is that supposed to live? – user1794918 Jan 15 '20 at 21:36
  • So, I had a thought that since the app>Patient.php (Which is the model) was basically empty. I move the first snippet of code into there. Then I get a new error htmlspecialchars() expects parameter 1 to be string, array given (View: /var/www/html/eastccm/resources/views/home.blade.php) – user1794918 Jan 15 '20 at 21:41
  • I removed the first block of code from the Patient model and the home page did load. And I could see that it did save the array. However, the home page will not load with that code in place. Where does the third block of code go? – user1794918 Jan 15 '20 at 21:55
  • @user1794918 sorry for my late reply. The third code snippet is just an example to show that the value should be casted back to array, it doesn't need to be included at all. The reported error in your second comment (htmlspecialchars()) is because the element is an array now, so you need to loop through it to get the every piece of data. In your third comment: If you remove the first code snippet, then it won't be casted back to array, that's why it loads the page, because it's a string (json). – Kenny Horna Jan 15 '20 at 22:59
  • I have to do a nested for each and I just get an error message when I try that. – user1794918 Jan 17 '20 at 15:33
  • I finally got the nested for each loop to work but how to get rid of that trailing bracket is a challenge. – user1794918 Jan 17 '20 at 21:29
  • @user1794918 what do you mean? Update your post with those details to be able to help you with that too :) – Kenny Horna Jan 17 '20 at 21:34
  • Kenny, notice I did not request help. The post is for others that stumble upon this post and are looking for a solution. It is a possible solution for them to try in their project. I am moving on and thanks for the advice. It's just that advice. There are many ways to code something out. I am offering options. I could have put the update under answering my own question. I choose not to. – user1794918 Jan 18 '20 at 14:07