-1

I am storing data from a form through an array to mysql database. Now I want to alert the user if he missed any field. So how can I alert him?

public function store(Request $request)
{
    $holiday = array (
        'firstname' => $request->firstname,
        'lastname' => $request->lastname,
        'startdate' => $request->startdate,
        'enddate' => $request->enddate
    );

    Holiday::create($holiday);

    return redirect()->route('holiday.index');
}
RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
anonymus
  • 161
  • 4
  • 12

1 Answers1

2

You can use Laravel's built in validation functionality for this. In your case, you might want to do something like this:

public function store(Request $request)
{
    $holiday = $request->validate([
        'firstname' => 'required',
        'lastname' => 'required',
        'startdate' => 'required',
        'enddate' => 'required'
    ]);

    Holiday::create($holiday);

    return redirect()->route('holiday.index');
}

Laravel will then ensure that those fields have been provided and if they haven't it will return the appropriate response. For example, if this is an API call it will return a 422 response with the error messages in. Or, if it is not an API call, it will return the user to the previous page and store the errors in the session for you to retrieve.

I'd recommend reading more about Laravel's validation techniques and all the things you can do with it. You can find more information about it here - https://laravel.com/docs/6.x/validation

George Hanson
  • 2,940
  • 1
  • 6
  • 18