Answer the question
In order to leave comments, you need to log in
How to create record in main table and in Laravel binder?
I need to create an API for a questionnaire. There are 3 tables/models Test, Question, Answer.
All connected in a one-to-many
chain
Route::post('test', 'Api\[email protected]');
public function createTest(Request $request)
{
$rules = [
'name' => 'required',
'question' => 'required',
];
$validator = Validator::make($request->all(), $rules);
if ($validator->fails()) {
return response()->json($validator->errors(), 400);
}
$test = Test::create($request->only('name'));
// а тут как-то еще нужно и вопросы записать..
return response()->json($test, 201);
}
class Test extends Model
{
public function questions()
{
return $this->hasMany(Question::class);
}
protected $fillable = [
'name',
];
}
class Question extends Model
{
public function test()
{
return $this->belongsTo(Test::class);
}
public function answers()
{
return $this->hasMany(Answer::class);
}
protected $fillable = [
'test_id',
'body',
];
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question