Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel validation: Call to a member function fails() on null

This piece of code was working a few days ago but I seem to have done something to cause it to break.

I have this route:

Route::post('admin/routemanagement', 'AdminController@addRoute');

Which looks like this:

    public function addRoute(Request $request) {
        if(Auth::check()) {
            $rules = [
                'flightDep' => 'required',
                'flightArr' => 'required',
                'flightDepTime' => 'required',
                'flightArrTime' => 'required',
            ];

            $messages = [
                'flightDep.required' => 'A departure ICAO is required',
                'flightArr.required' => 'An arrival ICAO is required',
                'flightDepTime.required' => 'A departure time is required',
                'flightArrTime.required' => 'An arrival time is required'
            ];


            $validator = $this->validate($request, $rules, $messages);

            if($validator->fails()) {
                return redirect('admin/routemanagement')->withErrors($validator)->withInput();
            }
     }

However when this code runs, the $validator variable ends up null for some reason and I get the following:

Call to a member function fails() on null

like image 595
Andrew De Forest Avatar asked Apr 20 '16 07:04

Andrew De Forest


1 Answers

From the Laravel Documentation:

"... if the validation fails, the proper response will automatically be generated. If the validation passes, our controller will continue executing normally." (https://laravel.com/docs/5.2/validation)

So the following code here is not necessary:

if($validator->fails()) {
            return redirect('admin/routemanagement')->withErrors($validator)->withInput();
        }

Laravel automatically responds if validation fails, and if it succeeds then the rest of your code executes normally.

like image 142
Josh R. Avatar answered Nov 06 '22 05:11

Josh R.