Categories
Learning

How to update in Laravel 8 all columns in database for form fields required and non required?

Hello, welcome to this question post.

I was looking for quick and succint turn around for this question and after searching lot on this one of post gave me any idea to update my rest of non-validate fields of form and also which don’t have validate rules at laravel model or controller level.

So here if my modified update() function from laravel Controller to update non required form fields or rules set in laravel controller or model, with in easy simple PHP style.

public function update(Request $request, $id)
    {
        
        $validatedData = $request->validate([
            'name' => 'required|max:255',
            'price' => 'required',
        ]);
        
        $nonRequiredFields = [
            'discount' => $request->discount,
            'qty' => $request->qty,
            'tax'=> $request->tax,
            'shipping' => $request->shipping,
            'handling' => $request->handling,
        ];
        
        Food::where('foodId', '=', $id)->update(array_merge($validatedData, $nonRequiredFields));
        
        return redirect()->route('food.index')->with('success', 'Food successfully updated');

}

In the code above I have given readable name to variable ($nonRequiredFields) which can be easily understand and I found this way the solution is working!

If you know more better approach kindly send me a not or if comments are open to this post please do comment.

Thanks for visiting and reading the post.