skip to Main Content

Well hello there,

When cleaning up my controller class I was wondering where to put extra fields when creating a model. In the StoreAdvertisementRequest class there are some validation rules applied.
Next I also want to make sure the new advertisement is coupled to a user_id and a certain status_id field.

But how does that work in combination with a make:request request and the method $request->validated().

Is there a way to sneak these in?

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());

4

Answers


  1. just merge the arrays

    $additionalFields = [
        'user_id' => Auth::id(), 
        'status_id' => AdvertisementStatus::WAITING_FOR_PROPOSAL,
    ];
    
    $advertisement = Advertisement::create(array_merge($request->validated(), $additionalFields));
    
    Login or Signup to reply.
  2. try this

    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);
    
    Login or Signup to reply.
  3. You first validate the request using the $request->validated() method, then add extra fields to the validated request data:

    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);
    
    }
    
    Login or Signup to reply.
  4. Just add this function to your ‘StoreAdvertisementRequest’ class,
    it will automatically appended to $request->validated().

    /**
     * Prepare the data for validation.
     */
    protected function prepareForValidation(): void
    {
        $this->merge([
            'user_id'   => Auth::id(),
            'status_id' => AdvertisementStatus::WAITING_FOR_PROPOSAL
        ]);
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search