Ad

How To Check Whether Array Elements Are Empty In Laravel?

- 1 answer

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

Answer

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

Ad
source: stackoverflow.com
Ad