Multiplo INSERT Models Laravel 5

Asked

Viewed 1,065 times

1

I am developing a system and came across the following situation:

I need to enter the data first in the 'person' table, retrieve the last 'id_person' and then insert the data in the 'provider' table all in the method store, note below what I have so far;

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 there’s something missing but I’m not sure what, when I execute the code to the table person receives the data, but the table supplier, receives nothing and returns the following error:

SQLSTATE[23502]: Not null Violation: 7 ERROR: null value in column "enrolled" violates the non-null restriction DETAIL: Registration that failed contains (13, 36, null). (SQL: Insert into "vendor" ("id_person") values (36) returning "id_supplier")

Someone has a suggestion?

  • You’re not passing anything on to Eloquent so he knows what he should have in the Vendor table. Just like you did the $request->all() and passed to the Pessoa::create... has to do for the supplier. Now, about the supplier id, I don’t understand what you really want... every supplier belongs to one person? How’s your model? Post your model here to help you better. If so, and if you have made the connections on the model, it will be very easy! I await details. Abs

3 answers

1

This is because the column cannot be null, ie in the vendor table ve be defined in your database as not null, or you set 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 directly in your database. Pộr NULL

And you inside the input array only have the id_pessoa Maybe what you want is this:

$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);
  • I need the data, they can’t be null.

  • So insert some data into that column, because the code you showed is not inserting anything into the column inscricao_estadual, and this is interpreted as null, and in your table this column cannot be null

  • When executing dd($datasPessoa = $request->all ()); I receive the data coming from the form, including enrolled_state, how to insert only this field in the supplier table?

  • And are you sure it’s not empty? And that the index of that value in the array $input is well written (inscricao_estadual) and is not empty?

  • Yes, note the return: array:10 [ "_token" => "Wrnruydorlvizdzzm3mg0wcjadtji7xtab48nyjr" "name" => "test" "document" => "00000" "entered state" => "0000000" "id_uf" => "8" "id_city" => "1" "cep" => "000000000" "address" => "000000" "neighborhood" => "00000000" "number" => "0000000" ]

  • All data is returned

  • You are only assigning a value and index to the array $input. He didn’t define anything else inside him

  • Any suggestions on how to do?

  • I still get the same error stating that NULL

  • In his model fornecedor, has inscricao_estadual in the array $fillable

  • 1

    @Miguel I’ve already specified this in my reply

  • I’m sorry, but I’m not controlling your response... I’m controlling mine in order to help the colleague. That’s what we want right

  • 1

    I still say that by the code that posted the array $input has nothing but id_pessoa

  • Exactly @Miguel, in fact there is, how can I capture this field "inscricao_estadual"?

Show 9 more comments

1

Friend. According to the error presented the entered field of your table supplier cannot be null and its variable $input does not seem to contain this field. I recommend you use the DB::transaction(function(){}); for control of querys in more than one table. This is because if you see an error the Rolback will automatically execute the information, 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 subscription_state field is set to not null you will not be able to do the Insert if a $input['inscricao_estadual'] = ''; In this case. This field must be validated for mandatory. To validate and ensure that the field will not be sent empty.

you have two options:

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

to create a request open your terminal and at the root of the project

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 that class containing the store method should contain the inclusion of that request

use app\Http\Requests\FornecedorRequest

Check if your Supplier model has the state-of-the-art Indice on $fillable

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

if not specified the model will ignore that field in Insert.

  • It was a good idea, but I really need that the registered field_state, be inserted in the table supplier, It is precisely what I could not do yet.

  • But by your code this information is not being passed. Hence the reason for the error

  • How could I use the $input variable to pass the state entry field_state?

  • I’ll put in answer

  • @geekcom edited my answer

  • I had not validated, it was very useful your answer, I am using Validator, but I still can not do the Insert.

Show 1 more comment

1


I thank everyone who has tried to help me in this matter, I have managed to resolve it in the following way:

   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 those who need help.

Browser other questions tagged

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