Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert record after Laravel form validation

I'm trying a Laravel 5.8 request validation. I managed to return errors and display them to my view. The problem is when I try to not trigger any validation rule, for whatever reason I cannot insert records into my table.

Error

Too few arguments to function App\Http\Requests\FieldRequest::Illuminate\Foundation\Providers{closure}(), 0 passed and exactly 1 expected

Controller

class FormController extends Controller
{
    public function create()
    {
        return view('create');
    }

    public function store(FieldRequest $req)
    {
        $validate_data = $req->validate();

        Form::create($validate_data);

        return redirect()->back()->with('message', 'Success!');
    }
}

FormRequest

class FieldRequest extends FormRequest
{
    public function authorize()
    {
        return true;
    }

    public function rules()
    {
        return [
            'item_name' => 'bail|required|max:255',
            'sku_no' => 'required|alpha_num',
            'price' => 'required|numeric',
        ];
    }

    public function messages()
    {
        return [
            'item_name.required' => 'An Item Name is required',
            'sku_no.required' => 'An SKU NO is required',
            'price.required' => 'The price is required',
        ];
    }
}

I'm expecting something to be inserted in my table. Do I need to perform the validation in my controller or not to achieve this? Thanks in advance!

like image 998
eugenebermudez Avatar asked Jul 09 '19 04:07

eugenebermudez


1 Answers

    public function store(FieldRequest $req)
    {
          $data = $req->all();           

          Form::create($data);

          return redirect()->back()->with('message', 'Success!');
    }

when you are working with form request you no need to use validate() function because your request goes in form request to validate your data then it will store records

like image 200
Karan Avatar answered Oct 26 '22 19:10

Karan