How to map and decode a json sql table in an edit in blade.php

I need to create an edit view in a blade.php in laravel that can map the info of the selected item in the table and let me modify it, whenver I try to made the edit I can only display the table but not the information of the selected item in the view, the information of the sql is stored in a json and need to be displayed with the selected checkboxes previously marked when saving the information

I have tried modifying the edit and the update function in my controller to receive the Json information from the sql table

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>public function edit($id)
{
$publicService = publicservices::findOrFail($id);
return view('publicServices.edit', compact('publicService'));
}
public function update(Request $request, $id)
{
$request->validate([
'tipoServicio' => 'required|array',
'proveedor' => 'required|array',
'costo' => 'required|array',
'nombrepropietario' => 'required|array',
'descripcion' => 'required|array',
'total' => 'required|numeric',
]);
$publicService = publicservices::findOrFail($id);
//here we collect the data and turned back into json
$services = [];
foreach ($request->tipoServicio as $service => $value) {
if ($value) { // Solo agregar servicios seleccionados
$services[$service] = [
'proveedor' => $request->proveedor[$service] ?? '',
'costo' => $request->costo[$service] ?? 0,
'nombrepropietario' => $request->nombrepropietario[$service] ?? '',
'descripcion' => $request->descripcion[$service] ?? '',
];
}
}
$publicService->servicios = json_encode($services);
$publicService->total = $request->total;
//Here the changes are saved
$publicService->save();
// Redireccionamos al índice con un mensaje de éxito
return redirect()->route('publicServices.index')->with('success', 'Servicio Público actualizado correctamente');
}
</code>
<code>public function edit($id) { $publicService = publicservices::findOrFail($id); return view('publicServices.edit', compact('publicService')); } public function update(Request $request, $id) { $request->validate([ 'tipoServicio' => 'required|array', 'proveedor' => 'required|array', 'costo' => 'required|array', 'nombrepropietario' => 'required|array', 'descripcion' => 'required|array', 'total' => 'required|numeric', ]); $publicService = publicservices::findOrFail($id); //here we collect the data and turned back into json $services = []; foreach ($request->tipoServicio as $service => $value) { if ($value) { // Solo agregar servicios seleccionados $services[$service] = [ 'proveedor' => $request->proveedor[$service] ?? '', 'costo' => $request->costo[$service] ?? 0, 'nombrepropietario' => $request->nombrepropietario[$service] ?? '', 'descripcion' => $request->descripcion[$service] ?? '', ]; } } $publicService->servicios = json_encode($services); $publicService->total = $request->total; //Here the changes are saved $publicService->save(); // Redireccionamos al índice con un mensaje de éxito return redirect()->route('publicServices.index')->with('success', 'Servicio Público actualizado correctamente'); } </code>
public function edit($id)
{
    $publicService = publicservices::findOrFail($id);

    return view('publicServices.edit', compact('publicService'));
}


public function update(Request $request, $id)
{
    $request->validate([
        'tipoServicio' => 'required|array',
        'proveedor' => 'required|array',
        'costo' => 'required|array',
        'nombrepropietario' => 'required|array',
        'descripcion' => 'required|array',
        'total' => 'required|numeric',
    ]);

    $publicService = publicservices::findOrFail($id);

    //here we collect the data and turned back into json
    $services = [];
    foreach ($request->tipoServicio as $service => $value) {
        if ($value) { // Solo agregar servicios seleccionados
            $services[$service] = [
                'proveedor' => $request->proveedor[$service] ?? '',
                'costo' => $request->costo[$service] ?? 0,
                'nombrepropietario' => $request->nombrepropietario[$service] ?? '',
                'descripcion' => $request->descripcion[$service] ?? '',
            ];
        }
    }
    $publicService->servicios = json_encode($services);
    $publicService->total = $request->total;

    //Here the changes are saved
    $publicService->save();

    // Redireccionamos al índice con un mensaje de éxito
    return redirect()->route('publicServices.index')->with('success', 'Servicio Público actualizado correctamente');
}

then trying to display in the edit.blade.php, but the previous image show the result of this

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>@extends('adminlte::page')
@section('title', 'Editar Servicio Público')
@section('content_header')
<h1>Editar Disponibilidad de Servicios Públicos</h1>
@stop
@section('content')
<div class="container">
<form method="POST" action="{{ route('publicServices.update', $publicService->id) }}">
@csrf
@method('PUT')
{{-- Tabla para editar los servicios públicos --}}
<table class="table table-bordered">
<thead>
<tr>
<th>Tipo de Servicio</th>
<th></th>
<th>Proveedor</th>
<th>Costo</th>
<th>A nombre de Quien</th>
<th>Descripción</th>
</tr>
</thead>
<tbody>
@php
$allServices = [
'Agua Potable', 'Electricidad', 'Alquiler', 'Cable Satelital',
'Internet', 'Celular', 'Alimentación', 'Prestamos', 'Otros',
'Cobro CANON', 'Avalúo ZMT'
];
// Decodificar el campo JSON de 'servicios' para obtener los valores actuales
$existingServices = json_decode($publicService->servicios, true);
@endphp
@foreach ($allServices as $service)
@php
// Cargamos los valores existentes del servicio o valores predeterminados
$selected = isset($existingServices[$service]);
$serviceData = $selected ? $existingServices[$service] : ['proveedor' => '', 'costo' => '', 'nombrepropietario' => '', 'descripcion' => ''];
@endphp
<tr>
<td>{{ $service }}</td>
<td>
<x-adminlte-input-switch name="tipoServicio[{{ $service }}]"
data-on-text="✓"
data-off-text="✕"
onchange="toggleInputs('{{ $service }}')"
{{ $selected ? 'checked' : '' }} />
<input type="hidden" name="selectedService[{{ $service }}]" id="selectedService-{{ $service }}" value="{{ $selected ? $service : '' }}" />
</td>
<td><x-adminlte-input name="proveedor[{{ $service }}]" value="{{ $serviceData['proveedor'] }}" {{ !$selected ? 'disabled' : '' }} /></td>
<td><x-adminlte-input name="costo[{{ $service }}]" type="number" step="1" value="{{ $serviceData['costo'] }}" {{ !$selected ? 'disabled' : '' }} oninput="calculateTotal()" /></td>
<td><x-adminlte-input name="nombrepropietario[{{ $service }}]" value="{{ $serviceData['nombrepropietario'] }}" {{ !$selected ? 'disabled' : '' }} /></td>
<td><x-adminlte-input name="descripcion[{{ $service }}]}" value="{{ $serviceData['descripcion'] }}" {{ !$selected ? 'disabled' : '' }} /></td>
</tr>
@endforeach
</tbody>
</table>
{{-- Total --}}
<div class="d-flex justify-content-end">
<x-adminlte-input name="total" id="total" label="Total" type="number" step="1" value="{{ $publicService->total }}" readonly />
</div>
{{-- Botones --}}
<div class="d-flex justify-content-between mt-3">
<x-adminlte-button type="submit" label="Guardar" theme="success"/>
<a href="{{ route('publicServices.index') }}" class="btn btn-danger">Cancelar</a>
</div>
</form>
</div>
@stop
@section('css')
{{-- no need of styles here --}}
@stop
@section('js')
<script>
// Función para habilitar o deshabilitar los campos según el checkbox
function toggleInputs(serviceName) {
const checkBox = document.querySelector(`input[name="tipoServicio[${serviceName}]"]`);
const hiddenInput = document.getElementById(`selectedService-${serviceName}`);
const fields = document.querySelectorAll(`input[name^="proveedor[${serviceName}]"], input[name^="costo[${serviceName}]"], input[name^="nombrepropietario[${serviceName}]"], input[name^="descripcion[${serviceName}]"]`);
fields.forEach(field => {
field.disabled = !checkBox.checked;
});
hiddenInput.value = checkBox.checked ? serviceName : '';
calculateTotal(); // Recalcular el total cuando se cambia el estado del checkbox
}
function calculateTotal() {
let total = 0;
const costFields = document.querySelectorAll('input[name^="costo["]');
costFields.forEach(field => {
if (!field.disabled && field.value) {
total += parseInt(field.value); // Convertir el valor a entero
}
});
document.getElementById('total').value = total;
}
</script>
@stop
</code>
<code>@extends('adminlte::page') @section('title', 'Editar Servicio Público') @section('content_header') <h1>Editar Disponibilidad de Servicios Públicos</h1> @stop @section('content') <div class="container"> <form method="POST" action="{{ route('publicServices.update', $publicService->id) }}"> @csrf @method('PUT') {{-- Tabla para editar los servicios públicos --}} <table class="table table-bordered"> <thead> <tr> <th>Tipo de Servicio</th> <th>✓</th> <th>Proveedor</th> <th>Costo</th> <th>A nombre de Quien</th> <th>Descripción</th> </tr> </thead> <tbody> @php $allServices = [ 'Agua Potable', 'Electricidad', 'Alquiler', 'Cable Satelital', 'Internet', 'Celular', 'Alimentación', 'Prestamos', 'Otros', 'Cobro CANON', 'Avalúo ZMT' ]; // Decodificar el campo JSON de 'servicios' para obtener los valores actuales $existingServices = json_decode($publicService->servicios, true); @endphp @foreach ($allServices as $service) @php // Cargamos los valores existentes del servicio o valores predeterminados $selected = isset($existingServices[$service]); $serviceData = $selected ? $existingServices[$service] : ['proveedor' => '', 'costo' => '', 'nombrepropietario' => '', 'descripcion' => '']; @endphp <tr> <td>{{ $service }}</td> <td> <x-adminlte-input-switch name="tipoServicio[{{ $service }}]" data-on-text="✓" data-off-text="✕" onchange="toggleInputs('{{ $service }}')" {{ $selected ? 'checked' : '' }} /> <input type="hidden" name="selectedService[{{ $service }}]" id="selectedService-{{ $service }}" value="{{ $selected ? $service : '' }}" /> </td> <td><x-adminlte-input name="proveedor[{{ $service }}]" value="{{ $serviceData['proveedor'] }}" {{ !$selected ? 'disabled' : '' }} /></td> <td><x-adminlte-input name="costo[{{ $service }}]" type="number" step="1" value="{{ $serviceData['costo'] }}" {{ !$selected ? 'disabled' : '' }} oninput="calculateTotal()" /></td> <td><x-adminlte-input name="nombrepropietario[{{ $service }}]" value="{{ $serviceData['nombrepropietario'] }}" {{ !$selected ? 'disabled' : '' }} /></td> <td><x-adminlte-input name="descripcion[{{ $service }}]}" value="{{ $serviceData['descripcion'] }}" {{ !$selected ? 'disabled' : '' }} /></td> </tr> @endforeach </tbody> </table> {{-- Total --}} <div class="d-flex justify-content-end"> <x-adminlte-input name="total" id="total" label="Total" type="number" step="1" value="{{ $publicService->total }}" readonly /> </div> {{-- Botones --}} <div class="d-flex justify-content-between mt-3"> <x-adminlte-button type="submit" label="Guardar" theme="success"/> <a href="{{ route('publicServices.index') }}" class="btn btn-danger">Cancelar</a> </div> </form> </div> @stop @section('css') {{-- no need of styles here --}} @stop @section('js') <script> // Función para habilitar o deshabilitar los campos según el checkbox function toggleInputs(serviceName) { const checkBox = document.querySelector(`input[name="tipoServicio[${serviceName}]"]`); const hiddenInput = document.getElementById(`selectedService-${serviceName}`); const fields = document.querySelectorAll(`input[name^="proveedor[${serviceName}]"], input[name^="costo[${serviceName}]"], input[name^="nombrepropietario[${serviceName}]"], input[name^="descripcion[${serviceName}]"]`); fields.forEach(field => { field.disabled = !checkBox.checked; }); hiddenInput.value = checkBox.checked ? serviceName : ''; calculateTotal(); // Recalcular el total cuando se cambia el estado del checkbox } function calculateTotal() { let total = 0; const costFields = document.querySelectorAll('input[name^="costo["]'); costFields.forEach(field => { if (!field.disabled && field.value) { total += parseInt(field.value); // Convertir el valor a entero } }); document.getElementById('total').value = total; } </script> @stop </code>
@extends('adminlte::page')

@section('title', 'Editar Servicio Público')

@section('content_header')
    <h1>Editar Disponibilidad de Servicios Públicos</h1>
@stop

@section('content')
    <div class="container">
        <form method="POST" action="{{ route('publicServices.update', $publicService->id) }}">
            @csrf
            @method('PUT')

            {{-- Tabla para editar los servicios públicos --}}
            <table class="table table-bordered">
                <thead>
                    <tr>
                        <th>Tipo de Servicio</th>
                        <th>✓</th>
                        <th>Proveedor</th>
                        <th>Costo</th>
                        <th>A nombre de Quien</th>
                        <th>Descripción</th>
                    </tr>
                </thead>
                <tbody>
                    @php
                        $allServices = [
                            'Agua Potable', 'Electricidad', 'Alquiler', 'Cable Satelital', 
                            'Internet', 'Celular', 'Alimentación', 'Prestamos', 'Otros', 
                            'Cobro CANON', 'Avalúo ZMT'
                        ];

                        // Decodificar el campo JSON de 'servicios' para obtener los valores actuales
                        $existingServices = json_decode($publicService->servicios, true);
                    @endphp

                    @foreach ($allServices as $service)
                        @php
                            // Cargamos los valores existentes del servicio o valores predeterminados
                            $selected = isset($existingServices[$service]);
                            $serviceData = $selected ? $existingServices[$service] : ['proveedor' => '', 'costo' => '', 'nombrepropietario' => '', 'descripcion' => ''];
                        @endphp

                        <tr>
                            <td>{{ $service }}</td>
                            <td>
                                <x-adminlte-input-switch name="tipoServicio[{{ $service }}]" 
                                    data-on-text="✓" 
                                    data-off-text="✕" 
                                    onchange="toggleInputs('{{ $service }}')" 
                                    {{ $selected ? 'checked' : '' }} />
                                <input type="hidden" name="selectedService[{{ $service }}]" id="selectedService-{{ $service }}" value="{{ $selected ? $service : '' }}" />
                            </td>
                            <td><x-adminlte-input name="proveedor[{{ $service }}]" value="{{ $serviceData['proveedor'] }}" {{ !$selected ? 'disabled' : '' }} /></td>
                            <td><x-adminlte-input name="costo[{{ $service }}]" type="number" step="1" value="{{ $serviceData['costo'] }}" {{ !$selected ? 'disabled' : '' }} oninput="calculateTotal()" /></td>
                            <td><x-adminlte-input name="nombrepropietario[{{ $service }}]" value="{{ $serviceData['nombrepropietario'] }}" {{ !$selected ? 'disabled' : '' }} /></td>
                            <td><x-adminlte-input name="descripcion[{{ $service }}]}" value="{{ $serviceData['descripcion'] }}" {{ !$selected ? 'disabled' : '' }} /></td>
                        </tr>
                    @endforeach
                </tbody>
            </table>

            {{-- Total --}}
            <div class="d-flex justify-content-end">
                <x-adminlte-input name="total" id="total" label="Total" type="number" step="1" value="{{ $publicService->total }}" readonly />
            </div>

            {{-- Botones --}}
            <div class="d-flex justify-content-between mt-3">
                <x-adminlte-button type="submit" label="Guardar" theme="success"/>
                <a href="{{ route('publicServices.index') }}" class="btn btn-danger">Cancelar</a>
            </div>
        </form>
    </div>
@stop

@section('css')
    {{-- no need of styles here --}}
@stop

@section('js')
    <script>
        // Función para habilitar o deshabilitar los campos según el checkbox
        function toggleInputs(serviceName) {
            const checkBox = document.querySelector(`input[name="tipoServicio[${serviceName}]"]`);
            const hiddenInput = document.getElementById(`selectedService-${serviceName}`);
            const fields = document.querySelectorAll(`input[name^="proveedor[${serviceName}]"], input[name^="costo[${serviceName}]"], input[name^="nombrepropietario[${serviceName}]"], input[name^="descripcion[${serviceName}]"]`);

            fields.forEach(field => {
                field.disabled = !checkBox.checked;
            });

            hiddenInput.value = checkBox.checked ? serviceName : '';

            calculateTotal(); // Recalcular el total cuando se cambia el estado del checkbox
        }

        function calculateTotal() {
            let total = 0;
            const costFields = document.querySelectorAll('input[name^="costo["]');

            costFields.forEach(field => {
                if (!field.disabled && field.value) {
                    total += parseInt(field.value); // Convertir el valor a entero
                }
            });

            document.getElementById('total').value = total;
        }
    </script>
@stop

1

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật