0
I am starting in Laravel and I have a problem related to inserting data in two tables of mysql... explaining better would be the following: I have a table called questionnaires where I have only ID and Description and another table called statements where I have the ID, a string question and another field called questionarios_id, and I have a form where I fill in the following fields: Description of questioning and question. What happens is that at the time I try to insert in the database when arriving at the table enuncias the value questionarios_id is not filled in occuring an error, I wonder if I have how to get the id inserted in my table questionnaires and usesTo fill in the question field
follows the codes:
model Questionario:
namespace App;
use Illuminate\Database\Eloquent\Model;
class Questionario extends Model
{
public $timestamps = false;
protected $fillable = array('descricao');
public function enunciado(){
return $this->hasMany('App\Enunciado');
}
}
model Enunciation:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Enunciado extends Model
{
public $timestamps = false;
protected $fillable = array('questao');
public function questionario(){
return $this->belongsTo('App\Questionario');
}
}
my controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Questionario;
use App\Enunciado;
use App\Http\Requests\QuestionarioRequest;
class ControllerPrincipal extends Controller
{
public function index(){
return view('ViewFormulario');
}
public function enviar(QuestionarioRequest $request){
Questionario::create($request->all());
Enunciado::create($request->all());
return redirect()->action('ControllerPrincipal@index');
}
}
the error that this code gives when sending the form is as follows:
QueryException in Connection.php line 647:
SQLSTATE[HY000]: General error: 1364 Field 'questionarios_id' doesn't have a default value (SQL: insert into `enunciados` (`questao`) values (teste))
id is injected into the object you just created, you would only need to place it in a variable and use, e.g.:
$q = Questionario::create(.... ;
and then catch with the $q->id`, but to mount a more complete answer.– Pliavi