Laravel从Form Submit调用多个控制器



我想提交一个表单,一旦按下提交按钮,我就会运行一些代码。在这段"代码"中,它的部分工作将是创建一个学生,并创建一个午餐订单。(从表格中提取的信息(。

根据我所读到的内容,我应该以使用CRUD为目标,这意味着我应该有一个Student Controller和一个LunchOrderController。

我想在每个控制器中调用@store方法。

如果我用"坏"的方式做,表单就会有[action="/students"method=POST]。在该路由中,它将调用/lunchorder/POST,然后返回到一个页面(重定向("students"((。

然而,如上所述,我不想从控制器调用控制器。因此,初始的[action="/students"method=POST]应该是其他的东西,然后这个新实体将调用StudentController,然后调用LunchOrderController,然后重定向("students"(。

但是,我不知道这个新实体是什么,或者应该是什么,也不知道如何链接到它

这只是一条通往新控制器的新路线,可以从中调用其他控制器吗?或者有没有其他地方我应该把表单数据发送到(也许是模型?(,让他们调用控制器?还是我离基地很远,需要退一步?

我对拉拉维尔还很陌生,但我想尽可能多地使用最佳实践。我对其他帖子的所有阅读似乎都不足以解释它,让我思考它是如何工作的。

编辑:一些代码可以让我知道我在做什么。

Student_edit.blade.php

<form action="/student" method="POST">
{{ csrf_field() }}
<label>First Name</label><input name="firstname"  value="">
<label>Last Name</label><input name="lastname"  value="">
<label>Lunch Order</label>
<select name="lunch_value" id="">
<option value="1" >Meat Pie</option>
<option value="2" >Sandwich</option>
<option value="3" >Salad</option>
<option value="4" >Pizza</option>
</select>

<input type="submit" value="Submit" class="btn btn-primary btn-lg">
</form>

web.php

Route::resource('/students', 'StudentController');
Route::resource('/lunchorder', 'LunchOrderController');

学生控制器

public function store(Request $request)
{
Student::create(request(['firstname', 'lastname']));
LunchOrderController::store($request, $student_id); //<- This isn't the correct syntax
return redirect('/students');  
}

LunchOrderController

public function store(Request $request, $student_id)
{
LunchOrder::create(array_merge(request(['lunch_value']), ['student_id' => $student_id]));
return null;  
}

就我个人而言,我会创建一个"逻辑"目录作为:app/Logic。有些人更喜欢存储库等,但这是我的偏好。对于您的具体要求,我会创建以下文件:

app/Logic/StudentLogic.php

StudentLogic

<?php
namespace AppLogicStudentLogic;
use AppStudent;
use AppLunchOrder;
class StudentLogic
{
public function handleStudentLunch(Request $request): bool
{
$student = Student::create(request(['firstname', 'lastname']));
if(is_null($student)) {
return false;
}

LunchOrder::create(array_merge(request(['lunch_value']), ['student_id' => $student->id]));
return true;
}
}

StudentController

public function store(Request $request)
{
$logic = new StudentLogic();
$valid = $logic->handleStudentLunch($request);
if($valid) {
return redirect('/students');  
}
abort(404, 'Student Not Found');
}

假设

Student存储在App/Student&LunchOrder存储在App\LunchOrder下您还需要在StudentController 中使用use AppLogicStudentLogic

我之所以将其拆分为Logic文件,是因为我不喜欢"重型"控制器。此外,我不完全确定你想在这里做什么,但根据与创建LunchOrder相同的请求创建一个学生似乎是在麻烦

最新更新