-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');
}
4

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your clear explanation, this helped me as am a beginner in laravel :-)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.