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
<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
<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