Save Relationships in Bank - Laravel 5.2

Asked

Viewed 660 times

1

What is the correct way to save related data in Laravel 5.2? I have a small application where I need to register data of a company and its address. When trying to save the data I get the error:

Tokenmismatchexception in Verifycsrftoken.php line 67:

But I’ve already set the Token in the view. In the controller I used Request::all() twice, to save the company and to save the address. That’s correct?

Follow Codes:

MODEL COMPANY

class Empresa extends Eloquent
{
    use SoftDeletes;
    protected $table   = 'empresas';
    public $timestamps = true;
    protected $guarded = ['id'];

    protected $fillable = array(
        'razao_social', 
        'nome_fantasia', 
        'cnpj', 
        'tipo_empresa',
        'tipo_cobranca',
        'telefone',
        'email',
        'numero_colaborador',
    );

    public function enderecos()
    {
        return $this->hasMany('SGW\Endereco');
    }
}

ADDRESS MODEL

class Endereco extends Model
{
    use SoftDeletes;
    protected $table   = 'enderecos';
    public $timestamps = true;
    protected $guarded = ['id'];

    protected $fillable = array(
        'cidade_id',
        'estado_id',
        'empresa_id',
        'endereco', 
        'numero', 
        'complemento', 
        'bairro',
        'cep',
        'tipo',
    );

    public function empresas()
    {
        return $this->belongsTo('SGW\Empresa');
    }
}

EMPRESASCONTROLLER

 public function store()
    {
        $empresa = Empresa::create(Request::all());
        $empresa->enderecos()->createMany(Request::all());

        Session::flash('flash_message', 'Empresa ' . Request::input('nome_fantasia') . ' cadastrada com sucesso!');
        return redirect()->action('EmpresaController@index');
    }

VIEW

@extends('layout.index') 
@section('titulo', 'CADASTRO DE EMPRESAS') 
@section('conteudo')

<div class="box-header with-border">

  <!-- Exibe a mensagem de retorno (Create, Update, Delete) -->
  @if(Session::has('flash_message'))
  <div class="alert alert-success alert-dismissable">
    <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
    <h4><i class="icon fa fa-check"></i> Sucesso!</h4>
    {{ Session::get('flash_message') }}
  </div>
  @endif


  <a href="{{ action('EmpresasController@index') }}" class="btn btn-info btn-lg pull-right">
    <i class="fa fa-building-o"></i> Lista de empresas
  </a>

</div>

<div class="box-body">

  <!-- form start -->
  <form action="{{ action ('EmpresasController@store') }}" method="post" class="form-horizontal  padding-left">

    <input type="hidden" name="_token" value="{{{ csrf_token() }}}" />

    <div class="box-body col-xs-6">
      <br />

      <div class="form-group">
        <div class="col-xs-12">
          <label for="razao_social">*Razão Social</label>
          <input type="text" class="form-control" name="razao_social" value="">
        </div>
      </div>

      <div class="form-group">
        <div class="col-xs-12">
          <label for="nome_fantasia">*Nome Fantasia</label>
          <input type="text" class="form-control" name="nome_fantasia" value="">
        </div>
        <div class="col-xs-7">
          <label for="cnpj">*CNPJ</label>
          <input type="text" class="form-control" name="cnpj" data-inputmask='"mask": "99.999.999/9999-99"' data-mask>
        </div>
      </div>

      <div class="form-group">
        <div class="col-xs-7">
          <label for="tipo_empresa">*Tipo Empresa</label>
          <select class="form-control" id="tipo_empresa" name="tipo_empresa">
            <option value=""></option>
            <option value="Empresário Individual">Empresário Individual</option>
            <option value="Microempreendedor Individual">Microempreendedor Individual</option>
            <option value="Sem fins lucrativos">Sem fins lucrativos</option>
            <option value="Sociedade Anônima">Sociedade Anônima</option>
            <option value="Sociedade em Comandita Simples">Sociedade em Comandita Simples</option>
            <option value="Sociedade Empresária">Sociedade Empresária</option>
            <option value="Sociedade Limitada">Sociedade Limitada</option>
            <option value="Sociedade Simples">Sociedade Simples</option>
          </select>
        </div>
      </div>

      <div class="form-group">
        <div class="col-xs-7">
          <label for="tipo_cobranca">*Tipo Cobrança</label>
          <select class="form-control" id="tipo_cobranca" name="tipo_cobranca">
            <option value=""></option>
            <option value="Adiantamentos">Adiantamentos</option>
            <option value="Cheque">Cheque</option>
            <option value="Depósitos">Depósitos</option>
            <option value="DOC">DOC</option>
            <option value="Duplicata">Duplicata</option>
            <option value="Ficha de Compensação">Ficha de Compensação</option>
            <option value="Ordem de Pagamento">Ordem de Pagamento</option>
            <option value="TED">TED</option>
          </select>
        </div>
      </div>


      <div class="form-group">
        <div class="col-xs-7">
          <label for="email">*E-mail</label>
          <input type="email" name="email" class="form-control" value="">
        </div>
      </div>

      <div class="form-group">
        <div class="col-xs-7">
          <label for="telefone">*Telefone</label>
          <input name="telefone" type="tel" class="form-control" data-inputmask='"mask": "(999) 99999-9999"' data-mask>
        </div>
      </div>

      <div class="form-group">
        <div class="col-xs-7">
          <label for="numero_colaborador">*Nº Colaboradores</label>
          <input name="numero_colaborador" type="number" class="form-control" value="">
        </div>
      </div>
    </div>

    <div class="box-body col-xs-1"></div>

    <div class="box-body col-xs-5">
      <br />
      <div class="form-group">
        <div class="col-xs-11">
          <label for="address">*Endereço</label>
          <input id="endereco" name="endereco" type="text" class="form-control">
        </div>
      </div>


      <div class="form-group">
        <div class="col-xs-4">
          <label for="numero">*Número</label>
          <input id="numero" name="numero" type="text" class="form-control">
        </div>
        <div class="col-xs-7">
          <label for="complemento">Complemento</label>
          <input id="complemento" name="complemento" type="text" class="form-control ">
        </div>
      </div>


      <div class="form-group">
        <div class="col-xs-7">
          <label for="bairro">*Bairro</label>
          <input id="bairro" name="bairro" type="text" class="form-control">
        </div>
        <div class="col-xs-4">
          <label for="cep">*Cep</label>
          <input id="cep" name="cep" type="text" class="form-control" data-inputmask='"mask": "99999-999"' data-mask>
        </div>
      </div>


      <div class="form-group">
        <div class="col-xs-11">
          <label for="estado">*Estado</label>
          <select class="form-control" id="estado_id" name="estado_id" required>
            <option value=""></option>
            @foreach ($estados as $e)
            <option value="{{$e->id}}">{{$e->nome}}</option>
            @endforeach
          </select>
        </div>
      </div>


      <div class="form-group">
        <div class="col-xs-11">
          <label for="cidade">*Cidade</label>
          <select class="form-control" id="cidade_id" name="cidade_id" required>
            <option value="">Selecione um Estado...</option>
          </select>
        </div>
        <input type="hidden" name="tipo" value="emp" id="tipo" />
      </div>

    </div>
    <!-- /.box-body -->

    <div class="box-body col-xs-12">
      <br />
      <button type="submit" class="btn btn-lg btn-success pull-right" data-loading-text="Cadastrando...">
        <i class="glyphicon glyphicon-save"></i> Cadastrar
      </button>
    </div>

  </form>

</div>
<!-- /.box-body -->
@stop @section('post-script')
<script type="text/javascript">
  $('select[name=estado_id]').change(function() {

    var idEstado = $(this).val();
    $('select[name=cidade_id]').empty();
    $('select[name=cidade_id]').append("<option value='' disabled selected style='display:none;'>Carregando...</option>");

    $.get("create/cidades/" + idEstado, function(cidades) {

      $('select[name=cidade_id]').empty();
      $('select[name=cidade_id]').append("<option value='' disabled selected style='display:none;'>Selecione uma cidade</option>");

      $.each(cidades, function(key, value) {
        $('select[name=cidade_id]').append('<option value=' + value.id + '>' + value.cidade + '</option>');
      });

    });
  });
</script>
@stop

I changed the store() from Empresascontroler to:

public function store()
{
    $endereco = new Endereco();
    $endereco->endereco    = Request::input('endereco');
    $endereco->numero      = Request::input('numero');
    $endereco->complemento = Request::input('complemento');
    $endereco->bairro      = Request::input('bairro');
    $endereco->estado_id   = Request::input('estado_id');
    $endereco->cidade_id   = Request::input('cidade_id');
    $endereco->cep         = Request::input('cep');
    $endereco->tipo        = Request::input('tipo');


    $empresa = Empresa::create(Request::all());
    $empresa->enderecos()->save($endereco);


    Session::flash('flash_message', 'Empresa ' . Request::input('nome_fantasia') . ' cadastrada com sucesso!');
    return redirect()->action('EmpresasController@index');
}

It worked but I don’t think it’s the right way to do it.

  • Have you tried printing the request? data dd(Request::all()); in the opening of the function store() of EMPRESASCONTROLLER

  • Already @Miguel, apparently everything is ok. I realized that the company data is being stored in the bank, already the address not, error occurs: Errorexception in Hasoneormany.php line 310: Argument 1 passed to Illuminate Database Eloquent Relations Hasoneormany::create() must be of the type array, string Given, called in C:wamp www SGW vendor Laravel framework src Illuminate Database Eloquent Relations Hasoneormany.php on line 335 and defined

  • The problem is in your view... is with three brackets... {{{...}}} in token. Put only {{ csrf_field() }} or leave two brackets like this: <input type="Hidden" name="_token" value="{{ csrf_token() }}" />. It should work. Abs

  • Certinho @Evert. I removed the brackets as told me. I also had to exchange the createMany for just create. Now it worked. Thanks.

1 answer

0


Friend you can insert as follows:

public function store(Request $request)
{
     try{
       \DB::transaction(function() use($request){

         $campos = $request->only([
            'nome_fantasia',
         ]);

          $endereco = $request->only([
          'endereco',
          'numero',
          'complemento',
          'bairro',
          'estado_id',
          'cidade_id',
          'cep',
          'tipo',
        ]);

         $empresa = Empresa::create($campos);

         $endereco['empresa_id'] =  $empresa->id;

         $endereco = Endereco::create($endereco);
     });

     Session::flash('flash_message', 'Empresa ' . $request->get('nome_fantasia') . ' cadastrada com sucesso!');
     return redirect()->action('EmpresaController@index');

    } catch (\Exception $e) {
     return $e->getMessage();
   }

}

You did not pass the request object as a parameter of your store method.

public function store(Request $request);

You use Request::all() for company and also for relationship. Is not trying to insert data from company table in address table no?

Note that I used the DB::transaction(); to perform the rolback in the bank if an error occurs. So you don’t run the risk of entering the company and not entering the address.

Browser other questions tagged

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