I can’t save all records from foreach - LARAVEL

Asked

Viewed 395 times

-1

In the user id it has 2 record only that at the time of saving it only saves 1 record and not the 2, as I must do to save correctly ?

Follows Code below

Controller Lists user data

public function listardados(){
    $matricula = Matricula::where('user_id', Auth::id())->get();

    //dd($matricula);
    return view('dashboard.renovacao.teste', compact( 'matricula'));
}

-- Controller Saves form record

public function store(RenovacaoRequest $request){


    $user = Auth()->user();

    $dados = $request->all();

    $renovacao = Renovacao::create($dados);


    return view('dashboard.renovacao.confirmacao', compact ('renovacao'));
}

-- View form

@extends('layouts.app') @section('content')

<div class="container">
    <div class="row">

        <form class="form-horizontal " id="regForm" action="{{route('renovacao.store')}}" method="POST">
            <div class="card-panel white">
                <h4 class="center">Solicitar Renovação</h4>
                <div class="row"></div>
                {{ csrf_field()}}
                <right>
                    <a>**Dados Cadastrados**</a>
                </right>
                <div class="row"></div>
                <div class="row"></div>
                <div class="row">
                    @foreach($matricula as $matric)
                    <div class="row">
                        <div class="col s6 m6">
                        <div class="input-field {{$errors->has('user_id') ? 'has-error' : ''}} ">
                            <label for="produto">Nome do Pai:</label>
                            <input type="text" class="form-control" name="nomerespo[]" value="{{ $matric->nomedopai }}">

                        </div>
                        </div>

                        <div class="col s6 m6">
                        <div class="input-field {{$errors->has('user_id') ? 'has-error' : ''}} ">
                            <label for="produto">Nome do Aluno(a):</label>
                            <input type="text" class="form-control" name="nomealuno[]" value="{{ $matric->nomealuno }}">    
                        </div>
                        </div>

                </div>
                @endforeach

                <div class = "row">
                    <div class="col s12">

                        <a title="Voltar Para Página Principal" class="btn orange darken-4 btn-info left " href="/admin">Voltar
                            <i class="material-icons left">arrow_back_ios</i>
                        </a>

                        <button type="submit" class="btn orange darken-4 btn-info right">Confirmar
                            <i class="material-icons left">save</i>
                        </button>
                    </div>
                </div>
            </div>
        </div>    
    </form>

</div>

@endsection

1 answer

0


Hello, the tags input in your form are with a fixed name within a @foreach this makes sending a form with multiple entries only one (of each name) is actually sent.

Try to change the following:

<input type="text" class="form-control" name="nomerespo" value="{{ $matric->nomedopai }}">
<input type="text" class="form-control" name="nomealuno" value="{{ $matric->nomealuno }}">

for:

<input type="text" class="form-control" name="nomerespo[]" value="{{ $matric->nomedopai }}">
<input type="text" class="form-control" name="nomealuno[]" value="{{ $matric->nomealuno }}">

Note that the attributes name the tags have been changed to a array, so all fields will be sent to your Controller

Case the relationship with Renovacao with user has been defined and the property $guarded or $fillable are defined in Renovacao can save the content with something of the form: $user->renovacoes()->saveMany($dados) and Laravel will handle the foreign key relationship for you.

Edit

The for loop of your form would look like this:

@foreach($matricula as $matric)
    <div class="row">
        <div class="col s6 m6">
        <div class="input-field {{$errors->has('user_id') ? 'has-error' : ''}} ">
            <label for="produto">Nome do Pai:</label>
            <input type="text" class="form-control" name="nomerespo[]" value="{{ $matric->nomedopai }}">

        </div>
        </div>

        <div class="col s6 m6">
        <div class="input-field {{$errors->has('user_id') ? 'has-error' : ''}} ">
            <label for="produto">Nome do Aluno(a):</label>
            <input type="text" class="form-control" name="nomealuno[]" value="{{ $matric->nomealuno  }}">
        </div>
        </div>

    </div>
@endforeach

The dd($request->all()) must return the following:

dd($request->all())

From your comments and prints I noticed that there is no relationship established in your Model User with the renovacao which I used as an example, so it is not possible to create with $user->renovacao()->createMany() or any other operation relating to $user->renovacao().

Edit 2

To leave documented, the array was not appearing in your dd, because it failed validation. Since HTML was changed to send an array it is necessary to change the validation rules as well:

[
   'nomerespo.*' => 'required|string|max:255',
   'nomealuno.*' => 'required|string|max:255',
]

This code validates the input as an array. To use the method create as you want it is necessary to change the HTML again:

<input type="text" class="form-control" name="rematricula[{{ $loop->index}}][nomerespo]" value="{{ $matric->nomedopai }}">
<input type="text" class="form-control" name="rematricula[{{ $loop->index}}][nomealuno]" value="{{ $matric->nomealuno }}">

Note that the input name has been changed to rematricula and there is one more level in the array.

Now in your Contoller you can do something like:

$dados = $request->get('rematricula');

foreach ($dados as $key => $dado) {
    Rematricula::create($dado);
}

I suggest checking the data input that the Controller is receiving and looking at the Laravel documentation (https://laravel.com/docs/5.7/eloquent#Inserts) to better understand the code.

  • Please avoid long discussions in the comments; your talk was moved to the chat

  • I just don’t understand this key in the foreach, where it comes from ?

  • <input type="" name="rematricula[{{ $loop->index}}][matricula_id]" value="{{ $Matric->id }}"> I added to come matricula_id as I set it to not appear in the form along with the others ?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.