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

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

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

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
}

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

Related

Laravel test kept failing due to wrong method

I have the following test to check my simple crud application in laravel.
I have my SalesManagersTest.php in tests/features
<?php
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
class SalesManagersTest extends TestCase
{
use RefreshDatabase;
public function test_can_see_index_screen()
{
$response = $this->get('/salesmanagers');
$response->assertStatus(200);
}
public function test_can_see_add_record_screen()
{
$response = $this->get('/salesmanagers/create');
$response->assertStatus(200);
}
public function test_can_add_new_record()
{
$response = $this->POST('/salesmanagers/create', [
'_token' => csrf_token(),
'full_name' => 'Test User',
'email' => 'test#example.com',
'telephone' => '0775678999',
'current_route' => 'Negombo',
'joined_date'=>'2022/09/12',
'comments' => 'Test comment'
]);
$response->assertStatus(200);
$response->assertRedirectedTo('salesmanagers');
}
}
The first two tests work well but the third test is giving me an error
but since I'm trying to insert new record the method has to be POST
this is my web.php
Route::get('/', [ SalesManagersController::class, 'index' ]);
Route::resource('salesmanagers', SalesManagersController::class);
Route::get('salesmanagers.create', [ SalesManagersController::class, 'create' ]);
Route::post('salesmanagers.create', [ SalesManagersController::class, 'store' ]);
What could be the the issue with my test?
The issue is your route definition. It appears you're using a route name for the URI of your route. Change your route to the following and try again:
Route::post('/salesmanagers', [SalesManagersController::class, 'store']);
Oh and POST your data to /salesmanagers not salesmanagers/create.

How to add custom form validation in Laravel?

I am trying to add custom validation in my controller.
<?php
namespace App\Http\Controllers;
use Auth;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Inertia\Inertia;
use Redirect;
use Response;
use Validator;
class MyController extends Controller
{
public function store(Request $req)
{
$v = Validator::make($req->all(), [
'contract_ref' => 'required'
]);
$v->after(function($v) use(&$req){
dd('custom validations');
// list of custom validations
if ($req->div_id == '') {
$validator->errors()->add('div_id', 'Please select a Division');
};
});
dd('NO!');
if ($v->fails()) {
//
}
$v->validate();
}
}
However, for some reason I don't understand. Nothing in the -after closure is being done. In example above, I get "NO!" dumped instead of the expected "custom validations"
This ->after has worked for me previously and I don't get why it is not working here.
Your are requesting dd('NO!') before the actual validate
try this :
<?php
namespace App\Http\Controllers;
use Auth;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Inertia\Inertia;
use Redirect;
use Response;
use Validator;
class MyController extends Controller
{
public function __contruct()
{
}
public function store(Request $req)
{
$v = Validator::make($req->all(), [
'contract_ref' => 'required'
]);
$v->after(function ($v) use (&$req) {
dd('custom validations');
// list of custom validations
if ($req->div_id == '') {
$validator->errors()->add('div_id', 'Please select a Division');
};
});
if ($v->fails()) {
//
}
$v->validate();
dd('NO!');
}
}
I reccomend using Closures https://laravel.com/docs/8.x/validation#using-closures as it can keep all of your validation logic in one place
use Illuminate\Support\Facades\Validator;
$validator = Validator::make($request->all(), [
'title' => [
'required',
'max:255',
function ($attribute, $value, $fail) {
if ($value === 'foo') {
$fail('The '.$attribute.' is invalid.');
}
},
],
]);
Have you used that?
$v->validate();
Below is an example of validation. You can also check your invalid input values inside fail check.
$validation_array = [
'id' => 'required',
'date' => 'required|date',
'material_type' => 'required',
'fabric' => 'required_if:material_type,==,0',
'color' => 'required_if:material_type,==,1',
'quantity' => 'required|numeric',
'unit' => 'required',
];
$validation_messages_array = [
'fabric.required' => 'The fabric field is required when material type is fabric.',
'color.required_if' => 'The color field is required when material type is blind.'
];
$validator = Validator::make(
$request->all(),
$validation_array,
$validation_messages_array
);
$validator->after(function ($validator) {
});
if ($validator->fails()) {
//code if not valid
}
$validator->validate();

test if user is logged in laravel 5.7

I am making a test but it fails when it tries to check if a user is logged in:
<?php
namespace Tests\Feature;
use Tests\TestCase;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Auth;
use App\User;
class RegisterTest extends TestCase
{
use RefreshDatabase;
/*.....
more test about registering
....*/
/** #test */
function redirect_to_home_page_and_logged_in_after_login()
{
$user = factory(User::class)->create([
'name' => 'Test',
'email' => 'test#hotmail.com',
'password' => '123456'
]);
$response = $this->post('login', [
'email' => 'test#hotmail.com',
'password' => '123456'
]);
//this works
$response->assertRedirect('/');
//this fails
$this->assertTrue(Auth::check());
}
}
And this is my controller HomeController:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class HomeController extends Controller
{
public function index()
{
if (Auth::check()){
return view('home');
}
return view('welcome');
}
}
And this is my routes/web.php
Route::get('/', 'HomeController#index');
Auth::routes();
I am not sure what I am doing wrong. What can I do?. I am using laravel 5.7 and phpunit 5.7.1
Also in my app/Htpp/Auth/LoginController.php I did this:
protected $redirectTo = '/';
Thank you.
In addition to hashing your password you could also just post to the register route and create a new account.
/** #test */
function redirect_to_home_page_and_logged_in_after_register()
{
$response = $this->post('register', [
'name' => 'Test',
'email' => 'test#hotmail.com',
'password' => '123456'
]);
//this works
$response->assertRedirect('/');
//this fails
$this->assertTrue(Auth::check());
}
I guess you may also have a requirement to do it both ways:
/** #test */
function redirect_to_home_page_and_logged_in_after_login()
{
$user = factory(User::class)->create([
'name' => 'Test',
'email' => 'test#hotmail.com',
// note you need to use the bcrypt function here to hash your password
'password' => bcrypt('123456')
]);
$response = $this->post('login', [
'name' => 'Test',
'email' => 'test#hotmail.com',
'password' => '123456'
]);
//this works
$response->assertRedirect('/');
//this fails
$this->assertTrue(Auth::check());
}
Creating a user requires you to take care of the hashing of the password.
You can simply do it by using php's password_hash function. And use Auth::login($user); to login.
Like so:
$user = User::create(['email' => 'r#o.b', 'password' => password_hash('123456', 1)]);
Auth::login($user); //You should be logged in :)

Error: Class Does not exist in Laravel

I am having the following error
InvalidArgumentException in FormBuilder.php line 39:
Form class with name App\Http\Controllers\App\Forms\SongForm does not exist.
on Laravel,
SongsController.php class
<?php
namespace App\Http\Controllers;
use Illuminate\Routing\Controller as BaseController;
use Kris\LaravelFormBuilder\FormBuilder;
class SongsController extends BaseController {
public function create(FormBuilder $formBuilder)
{
$form = $formBuilder->create(App\Forms\SongForm::class, [
'method' => 'POST',
'url' => route('song.store')
]);
return view('song.create', compact('form'));
}
public function store(FormBuilder $formBuilder)
{
$form = $formBuilder->create(App\Forms\SongForm::class);
if (!$form->isValid()) {
return redirect()->back()->withErrors($form->getErrors())->withInput();
}
// Do saving and other things...
}
}
SongForm.php
<?php
namespace App\Forms;
use Kris\LaravelFormBuilder\Form;
class SongForm extends Form
{
public function buildForm()
{
$this
->add('name', 'text', [
'rules' => 'required|min:5'
])
->add('lyrics', 'textarea', [
'rules' => 'max:5000'
])
->add('publish', 'checkbox');
}
}
routes.php
Route::get('songs/create', [
'uses' => 'SongsController#create',
'as' => 'song.create'
]);
Route::post('songs', [
'uses' => 'SongsController#store',
'as' => 'song.store'
]);
And I do not know where is the problem because the file exist in the project folder.
Explanation of the Error
Here:
$form = $formBuilder->create(App\Forms\SongForm::class, [
'method' => 'POST',
'url' => route('song.store')
]);
You're specifing the class name with a namespace relative to the current namespace:
App\Forms\SongForm::class
the full class name will be built relatively from the current namespace that is:
namespace App\Http\Controllers;
So, the class you're passing as parameter becomes:
App\Http\Controllers\App\Forms\SongForm::class
That class doesn't exists, and so you get the error
How to solve
To solve, you can specify the absolute namespace. Change this:
App\Forms\SongForm::class
to this:
\App\Forms\SongForm::class
and it should work

Custom Login System In Laravel

I create a customized login system in Laravel.
This is my controller:
<?php
namespace App\Http\Controllers;
use App\User;
use Illuminate\Support\Facades\Auth;
class Front extends Controller
{
public function register()
{
if (Request::isMethod('post')) {
User::create([
'name' => Request::get('name'),
'email' => Request::get('email'),
'password' => bcrypt(Request::get('password')),
]);
}
return Redirect::away('login');
}
public function authenticate()
{
if (Auth::attempt(['email' => Request::get('email'), 'password' => Request::get('password')])) {
return redirect()->intended('checkout');
} else {
return view('login', array('title' => 'Welcome', 'description' => '', 'page' => 'home'));
}
}
public function login()
{
return view('auth/login', array('page' => 'home'));
}
public function checkout()
{
return view('/aboutme', array('page' => 'home'));
}
}
And the routes are:
// Authentication routes...
Route::get('auth/login', 'Front#login');
Route::post('auth/login', 'Front#authenticate');
Route::get('auth/logout', 'Front#logout');
// Registration routes...
Route::post('/register', 'Front#register');
Route::get('/checkout', [
'middleware' => 'auth',
'uses' => 'Front#checkout'
]);
The error i am getting is:
FatalErrorException in Front.php line 12: Class
'App\Http\Controllers\Request' not found
You need to import Request. Add this to the top of your controller:
use Request;
By the way you will need to do this for the Redirect facade as well.
Your imports should look like this:
use Auth;
use Request;
use Redirect;
use App\Http\Controllers\Controller;
Try the following as it seems like you are not using Request specific namespace in your Front Controller:
use Illuminate\Http\Request;

Categories