I am blocked with the following array.
{"id":17,"user_id":1,"mails":"[\"hello\",\"Bye\"]","created_at":"2019-11-14 11:02:11", "updated_at":"2019-11-14 11:02:11"}
I need to show in a laravel view in one row mails: hello and in the next row mails: bye. But I can't access each element in all the ways I tried it always shows me:
["Hello bye"]
How can I access each of these properties and display them in the blade view?
In the controller that sends the data to the view:
public function index()
{
$datos = Mails::orderBy('id', 'DESC')->get();
// dd($datos);
// dd(json_decode($datos));
return view('Admin/Cuentas', compact('datos', $datos));
}
In the view I have this:
<table class="table table-striped table-bordered">
<thead>
<tr>
<th scope="col">N°</th>
<th scope="col">Usuario</th>
<th scope="col">Cuentas registradas</th>
<th scope="col">Fecha</th>
</tr>
</thead>
<tbody>
<?php $i=1; ?>
@foreach($datos as $usuario)
<tr>
<td>{{$i++}}</td>
<td>{{ $usuario->usuario_id }}</td>
<td>{{ $usuario['mails'] }}</td>
<td>{{ $usuario->created_at}}</td>
</tr>
@endforeach
</tbody>
</table>
I generate them in the view:
<form method="POST" action="/mailsEnviados">
@csrf
<div class="field_wrapper">
<div>
<input type="text" name="field_name[]" value=""/>
<a href="javascript:void(0);" class="add_button" title="Add field"><i class="fas fa-plus-circle"></i></a>
</div>
</div>
<button type="submit" class="btn btn-indigo">Enviar</button>
</form>
And I keep them:
$field_values_array = $_REQUEST['field_name'];
foreach($field_values_array as $value){
$mails = new Mails();
$mails->usuario_id = 1;
$mails->mails = json_encode($_REQUEST['field_name']);
$mails->save();
return 0;
}
Can you give me a hand please. Thank you very much!
From what you show, in the "mails" attribute, you don't have an array, but a string:
So to pass it to an array you can use json_decode :
And then loop through it with a foreach:
Or use implode :
With those two, all the elements of that array would be printed in the same row. But now that I reread the question, to print a row for each element, it would be like this:
Another approach, where you don't need the json_decode, would be to cast that attribute to an array in your Model:
https://laravel.com/docs/6.x/eloquent-mutators#array-and-json-casting