来自观察者 laravel 的访问表单请求

我正在尝试清理我的控制器。我有很多表单字段,所以我想使用观察者为与主模型有关系的其他模型插入


我已经成功地将请求插入到控制器中的数据库中,但它似乎又长又重。看下面的代码


function insert(Request $request){


 $bankStatementName = time().'.'.request()->bankStatement->getClientOriginalExtension();

request()->bankStatement->move(public_path('bankStatement'), $bankStatementName);


$identityName = time().'.'.request()->identity->getClientOriginalExtension();

request()->identity->move(public_path('identity'), $identityName);


 $passportName = time().'.'.request()->passport->getClientOriginalExtension();

request()->passport->move(public_path('passport'), $passportName);



 $customer = Customer::find(Auth::user()->id);


 $relations = new Customer_relationship([

                      'kinName' => $request->kinName,

                      'kinGender' => $request->kinGender,

                      'kinEmail' => $request->kinEmail,

                      'kinRelation' => $request->kinRelation,

                      'kinAddress' =>  $request->kinAddress

                  ]);

 $company = new Customer_company([

                'compName' => $request->compName,

                'compEmail' => $request->compEmail,

                'compPhone' => $request->compPhone,

                'compAddress' => $request->compAddress

             ]);

 $bank = new Customer_bank([

             'accNumber' => $request->accNumber,

             'bankName' => $request->bankName,

             'accName' => $request->accName

         ]);

 $document = new Customer_document([

        'identity' => $identityName,

        'bankStatement' => $bankStatementName,

        'passport' => $passportName

    ]);

 $customer->relation()->save($relations);

 $customer->company()->save($company);

 $customer->bank()->save($bank);

 $customer->document()->save($document);

}

那么如何从观察者的更新功能访问表单请求字段以进行控制器清理


喵喵时光机
浏览 182回答 1
1回答

斯蒂芬大帝

欢迎来到 SO!如果你想在这里使用观察者,你应该首先阅读https://laravel.com/docs/5.8/eloquent#observers和https://laravel.com/docs/5.8/queues如果您拥有父模型所需的所有数据,这可能会起作用,因为您只需将该模型传递给观察者触发的作业。如果不是,那么观察者/工作可能不是您的最佳解决方案。相反,我可能会创建某种服务,您可以在其中转移创建这些关系的责任。这样你就可以保持一个干净的控制器级别,它只调用一个服务来创建模型,然后返回结果。这方面的一个例子可能是:namespace App\Http\Controllers;use App\Models\Something\SomeService;class SomeController extends Controller{    /**     * @var SomeService      */    private $someService;    public function __construct(SomeService $someService)    {        $this->someService = $someService;    }    public function store()    {        $request = request();        $name    = $request->input('name');        $something = $this->someService->create($name);        return response()->json(['data' => $something]);    }}namespace App\Models\Something;class SomeService{    public function create(string $name): Something    {        // Do whatever in here...    }}这是我将如何做的一个简化示例。希望对你有所帮助。如果您仍然想使用工作来解决这个问题,那么我仍然认为观察者不是您的正确解决方案,因为它们是在模型事件上触发的,例如created. 这意味着你在那个时候将无法访问请求对象,而只是被创建(模型)。相反,您可以直接从控制器/服务分派作业。我在答案顶部发布的队列链接中对此进行了全部描述。
打开App,查看更多内容
随时随地看视频慕课网APP