php 在Laravel中传递附加字段以创建模型

h5qlskok  于 2023-10-15  发布在  PHP
关注(0)|答案(4)|浏览(137)

你好,
当清理我的控制器类时,我想知道在创建模型时在哪里放置额外的字段。在StoreAdvertisementRequest类中应用了一些验证规则。接下来,我还想确保新广告耦合到user_id和某个status_id字段。
但是如何将make:request请求和$request->validated()方法结合起来使用呢?
有办法把这些偷偷带进去吗?

public function store(StoreAdvertisementRequest $request): RedirectResponse
{
    // pass these in...
    $validated['user_id'] = Auth::id();
    $validated['status_id'] = AdvertisementStatus::WAITING_FOR_PROPOSAL;

    $advertisement = Advertisement::create($request->validated());
epggiuax

epggiuax1#

只要合并数组

$additionalFields = [
    'user_id' => Auth::id(), 
    'status_id' => AdvertisementStatus::WAITING_FOR_PROPOSAL,
];

$advertisement = Advertisement::create(array_merge($request->validated(), $additionalFields));
mklgxw1f

mklgxw1f2#

首先使用$request->validated()方法验证请求,然后向验证的请求数据添加额外的字段:

public function store(StoreAdvertisementRequest $request): RedirectResponse
{
    $validated = $request->validated();

    // Add extra fields
    $validated['user_id'] = Auth::id();
    $validated['status_id'] = AdvertisementStatus::WAITING_FOR_PROPOSAL;

    $advertisement = Advertisement::create($validated);

}
wsewodh2

wsewodh23#

只需将此函数添加到'StoreAdvertisementRequest'类中,它将自动附加到$request->validated()

/**
 * Prepare the data for validation.
 */
protected function prepareForValidation(): void
{
    $this->merge([
        'user_id'   => Auth::id(),
        'status_id' => AdvertisementStatus::WAITING_FOR_PROPOSAL
    ]);
}
piah890a

piah890a4#

试试这个

public function store(StoreAdvertisementRequest $request): RedirectResponse
{
    // pass these in...
    $validated['user_id'] = Auth::id();
    $validated['status_id'] = AdvertisementStatus::WAITING_FOR_PROPOSAL;

    $advertisement = Advertisement::create($request->validated() + $validated);

相关问题