Multiple INSERT Models Laravel 5

1

I'm developing a system and I came across the following situation:

I need to insert the data first into the 'person' table, retrieve the last 'person_id', and then insert the data into the 'provider' table everything in the store method, look below what I have up to now;

public function store(Request $request) {
    //capturar todos os dados digitados
    $dadosPessoa = $request->all ();

    //realizar insert via Eloquent e retornar o id_pessoa
    $id_pessoa = Pessoa::create ( $dadosPessoa )->id_pessoa;

    //id_pessoa na tabela pessoa é id_pessoa na tabela fornecedor 
    $input ['id_pessoa'] = $id_pessoa;

    Fornecedor::create ($input);
}

I know something is missing but I'm not sure what, when I run the code the table person receives the data, but the supplier table, receives nothing and returns the following error:

  

SQLSTATE [23502]: Not null violation: 7 ERROR: null value in column   "staple_info" violates non-null constraint DETAIL: Record that   failed contains (13, 36, null). (SQL: insert into "provider"   ("people_id") values (36) returning "provider_id")

Does anyone have a suggestion?

    
asked by anonymous 25.05.2016 / 21:24

3 answers

1

Thanks to everyone who tried to help me with this, I was able to solve it like this:

   public function store(Request $request) {

        //captura dados Model Pessoa
        $dadosPessoa = $request->except('inscricao_estadual');

        //captura dados Model Fornecedor
        $inscricao_estadual = $request->input('inscricao_estadual');

       //realizar insert via Eloquent e retornar o último id_pessoa
       $id_pessoa = Pessoa::create($dadosPessoa)->id_pessoa;    

       //realizar insert via Eloquent e retornar o último id_pessoa
       $fornecedor = Fornecedor::create(['id_pessoa' => $id_pessoa, 'inscricao_estadual' => $inscricao_estadual]);      

       flash()->success('Fornecedor adicionado com sucesso');
       return redirect()->action('FornecedorController@index');

}

Above is my complete method for anyone who needs help.

    
30.05.2016 / 16:57
1

Friend. According to the error presented, the field inscription_standard of your supplier table can not be null and its $input variable does not appear to contain this field. I recommend you use DB::transaction(function(){}); to control queries on more than one table. This is because if there is any error, laravel will automatically execute the information rollback, preventing the data from being inconsistent in your database. Ex:

  public function store(Request $request) {

      \DB::transaction(function() use($request) {

       $dadosPessoa = $request->all();

       $pessoa = Pessoa::create($dadosPessoa);

       $input['id_pessoa'] = $pessoa->id_pessoa;

       Fornecedor::create($input);

      });
  }

If in the database the field inscription_add is set to not null you will not be able to insert if the $input['inscricao_estadual'] = ''; In this case. This field must be validated to mandatory. To do the validation and ensure that the field will not be sent empty.

You have two options:

use validate() or request, follow the example that how to create the request for validation:

to create a request open your terminal and in the project root

php artisan make:request FornecedorRequest

Note that a request class will be created in app\Http\Requests

public function authorize()
{
      return true;
}


public function rules()
{
    $rules = [
        'inscricao_estadual' => 'required',
        'id_pessoa' => 'required'
    ];
    return $rules;
}

The parameter of your store method should be changed to

public function store(FornecedorRequest $request) 

and in this class containing the store method must contain the inclusion of this request

use app\Http\Requests\FornecedorRequest

Make sure your Provider model has the index iscricao_estadual in $fillable

protected $fillable = [
        'inscricao_estadual',
        'id_pessoa'
    ];

If not specified the model will ignore this field in the insert.

    
25.05.2016 / 21:33
1

This is because the column can not be null, that is, in the vend provider table that is defined in your database as not null , or you change the default for that column to accept null values. If you have created the tables in php (laravel) you can add:

Schema::create('products', function (Blueprint $table) {
...
   $table->string('inscricao_estadual')->nullable();
...
}

Or you can do this manually diratamente in your database. NULL

And you inside the input array only have id_pessoa maybe whatever this is:

$dadosPessoa = $request->except('_token'); // todos menos o _token
$id_pessoa = Pessoa::create ( $dadosPessoa )->id_pessoa;
$input['id_pessoa'] = $id_pessoa;
$input['inscricao_estadual'] = $dadosPessoa['inscricao_estadual'];
Fornecedor::create ($dadosPessoa);
    
25.05.2016 / 21:32