0

Tenho um form de cadastro de usuário no Laravel

<form class="form-horizontal" method="post" action="{{url('/usuarios')}}">
    @csrf

    @if(session()->has('message'))
        <div class="callout callout-danger">
            {{ session()->get('message') }}
        </div>
    @endif           

    <div class="box-body">

        <div class="form-group has-feedback {{ $errors->has('tipo') ? 'has-error' : '' }}">
            <label for="tipo" class="col-sm-2 control-label">Tipo</label>
            <div class="col-sm-10">
                <select id="tipo" class="form-control" name="tipo" required>
                    <option value="" selected>--- Escolha um tipo ---</option>
                    @foreach($tipos as $tipo)
                        <option value="{{ $tipo->id }}">{{$tipo->nome}}</option>
                    @endforeach
                </select>
                @if ($errors->has('tipo'))
                    <span class="help-block">
                        <strong>{{ $errors->get('tipo')[0] }}</strong>
                    </span>
                @endif
            </div>
        </div>

        <div class="form-group has-feedback {{ $errors->has('name') ? 'has-error' : '' }}">
            <label for="name" class="col-sm-2 control-label">Usuário</label>
            <div class="col-sm-10">
                <input type="text" class="form-control" name="name" placeholder="" minlength="4" maxlength="50" required>
                @if ($errors->has('name'))
                    <span class="help-block">
                        <strong>{{ $errors->get('name')[0] }}</strong>
                    </span>
                @endif
            </div>
        </div>

        <div class="form-group has-feedback {{ $errors->has('email') ? 'has-error' : '' }}">
            <label for="email" class="col-sm-2 control-label">Email</label>
            <div class="col-sm-10">
                <input type="emais" class="form-control" name="email" id="email" placeholder="" minlength="7" maxlength="50" required>
                @if ($errors->has('email'))
                    <span class="help-block">
                        <strong>{{ $errors->get('email')[0] }}</strong>
                    </span>
                @endif
            </div>
        </div>

        <div class="form-group has-feedback {{ $errors->has('password') ? 'has-error' : '' }}">
            <label for="password" class="col-sm-2 control-label">Senha</label>
            <div class="col-sm-10">
                <input type="text" class="form-control" name="password" id="password" placeholder="" minlength="6" maxlength="50" required>
                @if ($errors->has('password'))
                    <span class="help-block">
                        <strong>{{ $errors->get('password')[0] }}</strong>
                    </span>
                @endif
            </div>
        </div>

        <div class="form-group has-feedback {{ $errors->has('cidadao') ? 'has-error' : '' }}">
            <label for="cidadao" class="col-sm-2 control-label">Cidadão</label>
            <div class="col-sm-10">
                <select id="cidadao" class="form-control" name="cidadao" required>
                    <option value="" selected>--- Escolha um cidadão ---</option>
                    @foreach($cidadaos as $cidadao)
                        <option value="{{ $cidadao->id }}">{{$cidadao->nome}}</option>
                    @endforeach
                </select>
                @if ($errors->has('cidadao'))
                    <span class="help-block">
                        <strong>{{ $errors->get('cidadao')[0] }}</strong>
                    </span>
                @endif
            </div>
        </div>

    </div>

    <div class="box-footer">
        <button type="submit" class="btn btn-primary pull-right">Salvar</button>
    </div>

</form>

Com este tudo certo, no meu controller também, cadastra e o validator funciona bem

public function store(Request $request)
{
    $v = Validator::make($request->all(), [
        // user
        'tipo' => 'required|integer|not_in:--- Escolha um tipo ---',
        'name' => 'required|string|min:4|max:50|unique:users',
        'email' => 'required|string|email|min:7|max:50|unique:users',
        'password' => 'required|string|min:4|max:50',
        'cidadao' => 'required|integer|not_in:--- Escolha um cidadão ---',
    ]);

    if($v->fails()) {
        return back()->with('message', 'Confira os dados informados!')->withErrors($v)->withInput();
    }

    $user = new user;
    $user->name = $request->name;
    $user->email = $request->email;
    $user->password = Hash::make($request->password);
    $user->tipo_id = $request->tipo;
    $user->cidadao_id = $request->cidadao;
    $user->save();
    return redirect('/usuarios')->with('message', 'Cadastro realizado com sucesso!');
}

Porém gostaria que quando caísse no back() o form retornasse com os dados anteriormente preenchidos

Tentei algumas maneiras que pensei, a unica que funcionou foi colocar um form no @if(session()->has('message')) e retorno do $request preenchendo os campos, e outro form no @else dai normal

Porém acredito que deva ter alguma maneira mais pratica

1 Resposta 1

2

Aparentemente está tudo bem, à excepção de uma coisa que falta, old():

Nos values do form deves colocar, ex:

<input type="emais" class="form-control" value="{{old('email')}}" name="email" id="email" placeholder="" minlength="7" maxlength="50" required>

Para os selects:

<select id="tipo" class="form-control" name="tipo" required>
    <option value="" selected>--- Escolha um tipo ---</option>
    @foreach($tipos as $tipo)
        <option @if(old('tipo') == $tipo->id) selected @endif value="{{ $tipo->id }}">{{$tipo->nome}}</option>
    @endforeach
</select>

old() retorna null caso não haja withInput() na resposta, ou não haja input submitido com o name que entra como argumento em old().

DOCS

1
  • 1
    Muito obrigado, tava me batendo tentando aqui
    – Mateus
    18/04/2018 às 19:00

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .