Issue
I must save x2 the same data fields (nif
and name
) at the same time in the DB.
With 1 field (nif
) it works perfectly and save x2 rows in the DB with different info, so the JSON works, but adding the 2th field (name
) it just save the nif
value in all the fields.
I don't understand so much the JSON and his syntax logic, but I think the problem is how I wrote it in the controller.
P.D. No, I can't put EnviarCurriculumPreguntas::create
x2 in a row because that's not the purpose of this code, so I'm using a JSON instead.
EnviarCurriculum.php
namespace App;
use Illuminate\Database\Eloquent\Model;
class EnviarCurriculum extends Model
{
protected $table = 'table';
protected $primaryKey = 'ID_table';
protected $fillable = [
'nif',
'name'
];
public function getRepeatedFields()
{
return json_decode($this->nif);
return json_decode($this->name);
}
}
EnviarCurriculumController.php
namespace App\Http\Controllers\enviarCurriculum;
use App\EnviarCurriculum;
use App\Configuracion;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class EnviarCurriculumController extends Controller
{
public function index()
{
return view('enviar_curriculum', ['EnviarCurriculum' => new EnviarCurriculum()]);
}
public function create()
{
return view('enviar_curriculum', ['EnviarCurriculum' => new EnviarCurriculum()]);
}
public function store(Request $request)
{
foreach (request('nif', 'name') as $val) {
EnviarCurriculum::create(['nif' => $val, 'name' => $val]);
}
}
}
enviar_curriculum.blade.php
<!DOCTYPE html>
<html lang="es">
<head>
...
</head>
<body>
<form action="{{ route("store") }}" method="POST">
@csrf
<div>
<input type="text" name="nif[]" id="nif">
<input type="text" name="name[]" id="name">
</div>
<br>
<div>
<input type="text" name="nif[]" id="nif">
<input type="text" name="name[]" id="name">
</div>
<input type="submit" class="btn btn-primary" value="Enviar">
</form>
</body>
</html>
Solution
you can't have input having the same name without being an array
<!DOCTYPE html>
<html lang="es">
<head>
...
</head>
<body>
<form action="{{ route("store") }}" method="POST">
@csrf
<div>
<input type="text" name="nif[]" id="nif">
<input type="text" name="name[]" id="name">
</div>
<br>
<div>
<input type="text" name="nif[]" id="nif">
<input type="text" name="name[]" id="name">
</div>
<input type="submit" class="btn btn-primary" value="Enviar">
</form>
</body>
</html>
Then in your store method loop the array inputs
public function store(Request $request)
{
$nifs = $request->input('nif', []);
$names = $request->input('name', []);
foreach ($nifs as $key => $nif) {
EnviarCurriculum::create(['nif' => $nif, 'name' => $names[$key]??'']);
}
}
Then fix your getRepeatedFields()
method to return both decoded fields.
public function getRepeatedFields()
{
return [
'nifs' => json_decode($this->nif),
'names' => json_decode($this->name),
];
}
Answered By - N69S Answer Checked By - Robin (PHPFixing Admin)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.