在 laravel 中向 2 个控制器提交一份表格

one form submision to 2 controllers in laravel

所以我的数据库中有 2 个表:example students and hobbies。 所以这意味着 2 个控制器以及 StudentController 和 HobbyController。 以及 2 个模型。

我有一个表格,例如:

前五个必须交给studentcontroller 6-9 转到 hobbycontroller.. 我该怎么做?我不想要 2 种不同的形式 ...

这可能不是最佳答案,但您可以使用单一表单传递给控制器​​,然后将数据传递给多个存储库。

route.php

Route::resource('student', 'StudentController');

StudentController.php

public function __constructor(StudentRepository $student, HobbyRepository $hobby)
{
    $this->student = $student;
    $this->hobby= $hobby;
}

public function store(Request $request)
{
    $data = $request->all();
    $hobby = [
        'hobby' => $data['hobby'],
        'schedule' => $data['schedule'],
        'intensity' => $data['intensity'],
        'diet' => $data['diet'],
    ];
    $student = [
        'student_name' => $data['student_name'],
        'age' => $data['age'],
        'height' => $data['height'],
        'weight' => $data['weight'],
        'bmi' => $data['bmi'],
    ];

    $this->student->store($student);
    $this->hobby->store($hobby);

    //your other codes.
}

StudentRepository.php

public function store($data)
{
   // your implementation on storing the user.
}

HobbyRepository.php

public function store($data)
{
   // your implementation on storing the hobby.
}

您可以使用任何方法和变量从控制器传递数据。希望这会有所帮助。

编辑:

关于存储和检索信息的扩展问题。

如文档中所述:

The create method returns the saved model instance:

$flight = App\Flight::create(['name' => 'Flight 10']);

有关更多信息,请参阅文档:

https://laravel.com/docs/5.3/eloquent#inserts

如果你想把 student id 传给 hobby 最简单的方法是把 return 来自 StudentRepository 的学生传给 HobbyRepository.

例如:

StudentRepository.php

public function store($data)
{
   // your implementation on storing the user.
   $student = [] // array of the student informations to be stored.
   return Student::create($student); //you will have student information here.
}

StudentController.php

$student = $this->student->store($student); //store the student information and get the student instance.
$this->hobby->store($hobby, $student->id); //pass it to the hobby to store id.

您应该将 hobbyRepository 商店更改为使用 student id

这可能会解决您的扩展问题。