Skip to content
Advertisement

Laravel Storage Multiple Value Json Format

I am trying to throw SQL information in JSON format from the form. I saved the information in the SQL area, but it saves it in the form of SQL escape. When I shoot with API, I can’t use it as I want. The codes are as follows. I wonder where I am making mistakes, but I could not find a solution.

Migrate for workers column

$table->text('workers')->nullable();

Model I wrote that the workers’ column in the table is in an array format

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

Blade or view It is necessary to save multiple data here such as name, id

<select class="js-example-basic-multiple searchselect form-control show-tick" name="workers[]" multiple="multiple">
     @foreach ($personels as $personel)
<option value='{"spid":{{ $personel->id }},"spsicil":{{ $personel->sicil_no }},"spname":"{{ $personel->name }}"}'>{{ $personel->name }}</option>
     @endforeach
</select>

Controller File

 $workers = implode(',', $request->workers);
 $new = "[".$workers."]";
        $data = new Zimmet();
        $data->name = $request->name;
        $data->sicil_no = $request->sicil_no;
        $data->proje_id = $request->proje_id;
        $data->workers = $new;
        $data->save();

I got used to converting the incoming data to array format, but I’m not sure of the correct one.

It records the workers column in the table as follows.

"[
{"spid":1,"spsicil":35678909,"spname":"Mike"},
{"spid":5,"spsicil":3,"spname":"Jhon"},
{"spid":4,"spsicil":44,"spname":"Erica"}
]"

Multiple Value How do I correctly add to the database in array or json format.

Thank you for your advice and help

Advertisement

Answer

The issue over here is, the string is JSONified twice.

I would suggest you remove the following lines from your code

$workers = implode(',', $request->workers);
$new = "[".$workers."]";

Updated code should be:

    $data = new Zimmet();
    $data->name = $request->name;
    $data->sicil_no = $request->sicil_no;
    $data->proje_id = $request->proje_id;
    $data->workers = $request->workers;
    $data->save();

Explanation:

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

Takes care of Serialization and Deserialization of Array to JSON while storing into the Database and fetching from Database.

I hope, this will help you.

Best.

Reference: https://laravel.com/docs/7.x/eloquent-mutators#array-and-json-casting

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement