D
D
Dima2020-09-22 15:24:11
Laravel
Dima, 2020-09-22 15:24:11

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]');

In TestController I describe the createTest(Request $request) method.

It is assumed that the data is entered as follows: The name of the test (in the tests table) and one or more questions (in the questions table). And here's the question: How to organize this method so that data is written to 2 tables at once, and if there are several questions, then all of them are associated with the same test?

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 question

Ask a Question

731 491 924 answers to any question