php – Laravel 7 "Class 'App\Http\Controllers\Validator' not found"-ThrowExceptions

Exception or error:

A few days ago I started learning laravel 7.
I bought a course on udemy.
I got to the part where the real registry system went and started to rewrite the code like in the video, but when I do it I get an error!

Error Message: "Class 'App\Http\Controllers\Validator' not found"

I’ve been trying to fix this for hours, and I’m not doing well

AccountController.php

<?php

namespace App\Http\Controllers;

class AccountController extends Controller
{
    public function getcreate(){
        return view('account.create');
    }

    public function postcreate(){
        $validator = Validator::make(Input::all(), 
        array(
            'email'  =>      'required|max:50|email|unique:users',
            'username' =>    'required|max:20|min:3|unique:users',
            'password' =>    'required|min:6',
            'repeat_pass' => 'required|same:password'   
        ));

        if($validator->fails()){
            die('ERROR');
        }
        else{
            die('Cool');
        }
    }
}
How to solve:

you need to import validator namespace

use Illuminate\Support\Facades\Validator;

then instead of Input you could use request()->all() helper function

so it will be like this

namespace App\Http\Controllers;
use Illuminate\Support\Facades\Validator;

class AccountController extends Controller
{
    public function getcreate(){
        return view('account.create');
    }

    public function postcreate(){
        $validator = Validator::make(request()->all(), 
        array(
            'email'  =>      'required|max:50|email|unique:users',
            'username' =>    'required|max:20|min:3|unique:users',
            'password' =>    'required|min:6',
            'repeat_pass' => 'required|same:password'   
        ));

        if($validator->fails()){
            die('ERROR');
        }
        else{
            die('Cool');
        }
    }
}

Answer:

You will need to import the Validator class from it’s correct namespace which is Illuminate\Support\Facades. So goes with Input class. Best way I can suggest is to add these in aliases section in config\app.php like below:

 'aliases' => [
     // other imports
     'Validator' => Illuminate\Support\Facades\Validator::class,
     'Input' => Illuminate\Support\Facades\Input::class,
 ]

Now, you can simply use them in your controller like below:

<?php

namespace App\Http\Controllers;
use Validator;
use Input;


class AccountController extends Controller
{
 // rest of your code
}

Answer:

You can use Validator namespace in your controller at top like:

use Validator;

Leave a Reply

Your email address will not be published. Required fields are marked *