Slim Application Error: Respect\Validation\Validator - php

I get this error when trying to Validate my OrderForm.php. If someone followed Codecourse Shopping Cart Tutorial you may know why I get this error. Here is my code in some of my files that I think is most relevant to this error and of course the error.
Error:
Message: Class 'Respect\Validation\Validator' not found
File: PATH/cart/app/Validation/Forms/OrderForm.php
on 13
I will also post this image of my Directory Folders:
Directory Folder Image
OrderForm.php
<?php
namespace Cart\Validation\Forms;
use Respect\Validation\Validator as v;
class OrderForm
{
public static function rules()
{
return [
'email' => v::email(),
'name' => v::alpha(' '),
'address1' => v::alnum(' -'),
'address2' => v::optional(v::alnum(' -')),
'city' => v::alnum(' '),
'postal_code' => v::alnum(' '),
];
}
}
Validator.php
<?php
namespace Cart\Validation;
use Cart\Validation\Contracts\ValidatorInterface;
use Psr\Http\Message\ServerRequestInterface as Request;
use Respect\Validation\Exceptions\NestedValidationException;
class Validator implements ValidatorInterface
{
protected $errors = [];
public function validate(Request $request, array $rules)
{
foreach ($rules as $field => $rule) {
try {
$rule->setName(ucfirst($field))->assert($request->getParam($field));
} catch (NestedValidationException $e) {
$this->errors[$field] = $e->getMessages();
}
}
$_SESSION['errors'] = $this->errors;
return $this;
}
public function fails()
{
return !empty($this->errors);
}
}
ValidatorInterface.php
<?php
namespace Cart\Validation\Contracts;
use Psr\Http\Message\ServerRequestInterface as Request;
interface ValidatorInterface
{
public function validate(Request $request, array $rules);
public function fails();
}
Edit: I just want to say that I changed:
use Respect\Validation\Validator as v;
to
use Cart\Validation\Validator as v;
And then I get a completely new error so that did that work.

It seems to me that you may be missing a dependency file such as respect/validation as some elements are installed during the video tutorials, I would recommend watching the video(s) concerning any of the validation routines, as the codecourse "Authentication with Slim 3:", installs additional addons/components with package managers such as composer, during the tutorial which may have been missed.

Well it tells you where the error is:
Message: Class 'Respect\Validation\Validator' not found
Path to that class is not valid, or that file is not on that path. I'm not completely sure but if you write it like you did use Respect\Validation\Validator as v; the final path will be current namespace plus that path Cart\Validation\Forms\Respect\Validation\Validator.
File: PATH/cart/app/Validation/Forms/OrderForm.php on 13
This second part is just were it triggered the error, on line 13 'email' => v::email(),.
Edit:
I just saw that image, the path should be use \App\Validation\Validator

Related

laravel:8 Class 'App\Http\Controllers\Tag' not found

I tried to show and create tags but it showed an error "Error
Class 'App\Http\Controllers\Tag' not found
http://127.0.0.1:8000/articles/create/"
error line:
'tags' => Tag::all()
code:
public function create()
{
return view('articles.create', [
'tags' => Tag::all()
]);
}
use App\Models\Tag;
you are using model without using it in controller.

how to solve getting 404 in Laravel 5.4 : Api route list

I am getting 404 while am trying to access my api url here is my route :
MY Api route list:
<?php
use Illuminate\Http\Request;
Route::middleware('auth:api')->get('/', function (Request $request) {
return $request->user();
});
Route::get('testapi','ApiDoctorController#testapi');
and the controller function that is provide data response is :
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class ApiDoctorController extends Controller
{
public function testapi(){
$data = [
'name' => 'HEllo',
'age' => '24',
'height' => '5.4'
]
return response()->json($data);
}
}
When i try to access it in post-man at http://mydomain/project/api/testapi
its showing 404 error i am new to laravel help me out please
[![POSTMAN RESPONSE][1]][1][1]: https://i.stack.imgur.com/1uV6Z.png
First of all your missing the semicolon on the end of your data array.
Is Route::get('testapi','ApiDoctorController#testapi'); in your routes/api.php?
If not you'll need to define it so.
In postman you're doing domain/project/api/testapi when it should be domain/api/testapi as that is what you have specified in your routes file unless your entire laravel install is in domain/project.
I have added the semi-colon for you and formatted the code. If you're testing via postman please ensure that CSRF is disabled in your App/Http/Kernel.php (Just comment it out for your testing) then place it back in when you've setup authentication.
Let me know if this helps!
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class ApiDoctorController extends Controller
{
public function testapi()
{
$data = [
'name' => 'Hello',
'age' => '24',
'height' => '5.4'
];
return response()->json($data);
}
}
Thanks everyone i got it i just add public after my project directory and it work thanks to all of you for your valuable time

Laravel 5.5 phpunit testing form validation

I'm trying to write some tests for my forms in order to confirm the validators retrieve the expected errors when required.
The form only has 3 fields: name, discount and expiration and the validator looks like this:
$this->validate($request, [
'name' => 'required',
'discount' => 'required|numeric|between:1,100',
'expiration' => 'required|date_format:d/m/Y',
]);
That works fine both when submitting the form and when running the tests with phpunit using the following code:
/**
* Discount must be numeric check
*/
$response = $this->post(route('offer.create'), [
'name' => $faker->sentence(4),
'discount' => 'asdasd',
'expiration' => $faker->dateTimeBetween('+1 days', '+5 months')
]);
// Check errors returned
$response->assertSessionHasErrors(['discount']);
Since discount is not numeric it throws the expected error and everybody is happy.
Now, if I want to add a new rule to make sure that the expiration is equal or greater to today I add the after:yesterdayrule leaving the validator like:
$this->validate($request, [
'name' => 'required',
'discount' => 'required|numeric|between:1,100',
'expiration' => 'required|date_format:d/m/Y|after:yesterday',
]);
That works fine when submitting the form. I get the error saying the discount is not numeric, but when testing with phpunit it doesn't get the error as expected:
1) Tests\Feature\CreateSpecialOfferTest::testCreateSpecialOffer
Session missing error: expiration
Failed asserting that false is true.
Why adding this new validation rule to expirationgenerates a false validation in discount? Is this a bug in the validator or am I missing something?
Also:
1 - is there a better way to test form validators?
2 - is there an assert that is the opposite of assertSessionHasErrors() to check a certain error is NOT been thrown?
If you see this kind of errors in PHPUnit: Failed asserting that false is true., you can add the 'disableExceptionHandling' function to tests/TestCase.php:
<?php
namespace Tests;
use Exception;
use App\Exceptions\Handler;
use Illuminate\Contracts\Debug\ExceptionHandler;
use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
abstract class TestCase extends BaseTestCase
{
use CreatesApplication;
protected function disableExceptionHandling()
{
// Disable Laravel's default exception handling
// and allow exceptions to bubble up the stack
$this->app->instance(ExceptionHandler::class, new class extends Handler {
public function __construct() {}
public function report(Exception $exception) {}
public function render($request, Exception $exception)
{
throw $exception;
}
});
}
}
In your test you call it like this:
<?php
/** #test */
public function your_test_function()
{
$this->disableExceptionHandling();
}
Now, the full output of the error and stacktrace will be shown in the PHPUnit console.

Laravel validator throws an exception instead of redirecting back

After I upgraded to Laravel 5.2 I encountered a problem with the laravel validator. When I want to validate data in a controller take for example this code.
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
class ContactController extends Controller
{
public function storeContactRequest(Request $request)
{
$this->validate($request, [
'_token' => 'required',
'firstname' => 'required|string'
'lastname' => 'required|string'
'age' => 'required|integer',
'message' => 'required|string'
]);
// Here to store the message.
}
}
But somehow when I enter unvalid data it will not redirect me back to the previous page and flash some messages to the session but it will trigger an exception and gives me a 500 error page back.
This is the exception I get.
I have read in the documentation that the ValidationException is new instead of the HttpResponseException but I don't know if it has anything to do with this.
[2016-01-05 11:49:49] production.ERROR: exception 'Illuminate\Foundation\Validation\ValidationException' with message 'The given data failed to pass validation.' in /home/vagrant/Code/twentyre-webshop/vendor/laravel/framework/src/Illuminate/Foundation/Validation/ValidatesRequests.php:70
And when I use a seperate request class it will just redirect back with the error messages. It seems to me only the validate method used in a controller is affected by this behaviour.
Update your App\Exceptions\Handler class
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Illuminate\Foundation\Validation\ValidationException;
/**
* A list of the exception types that should not be reported.
*
* #var array
*/
protected $dontReport = [
AuthorizationException::class,
HttpException::class,
ModelNotFoundException::class,
ValidationException::class,
];
I also recommend you to read the docs how to migrate to laravel 5.2, because there were some breaking changes. For example this, ValidatesRequests trait throws
Illuminate\Foundation\Validation\ValidationException instead of Illuminate\Http\Exception\HttpResponseException
Documentation how to migrate from Laravel 5.1 to 5.2
Example from laravel docs. You can use Validator facade, for custom validation fails behaviour
public function store(Request $request)
{
$validator = Validator::make($request->all(), [
'title' => 'required|unique:posts|max:255',
'body' => 'required',
]);
if ($validator->fails()) {
return redirect('post/create')
->withErrors($validator)
->withInput();
}
// Store the blog post...
}
This is how I handle it in Laravel 5.3 (by modifying Handler.php)
https://stackoverflow.com/a/42852358/3107185
For laravel 5.2 I had to add this line:
if ($e instanceof ValidationException)
{
return redirect()->back()->withInput();
}
In App\Exceptions\Handler.php,and the following headers:
use Illuminate\Session\TokenMismatchException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Validation\ValidationException;
use Illuminate\Auth\AuthenticationException;
For my purpose, I was bulding a fully API based application in Laravel 5.3 which I had manually upgraded from Laravel 5.1. and I just needed Laravel to respond back with the validation errors that needed fixing on my FormRequest.
Adding this line:
elseif ($e instanceof ValidationException)
{
return $this->convertValidationExceptionToResponse($e, $request);
}
after this one:
if ($e instanceof ModelNotFoundException) {
$e = new NotFoundHttpException($e->getMessage(), $e);
}
In App\Exceptions\Handler.php did the trick for me and returned expected validation errors when using FormRequest validation.
Please see my comments here: #ratatatKE's comments on github
might save someone time, Another issue is that you are calling validator->validate() in the view, not in the controller
i was calling in the view because i have a lazy load component that triggered on the view
I had the same problem when upgrading 4.2 to 5.3.
This answer worked for me.
Override the method in app/Exceptions/Handler.php
protected function convertExceptionToResponse(Exception $e)
{
if (config('app.debug')) {
$whoops = new \Whoops\Run;
$whoops->pushHandler(new \Whoops\Handler\PrettyPageHandler);
return response()->make(
$whoops->handleException($e),
method_exists($e, 'getStatusCode') ? $e->getStatusCode() : 500,
method_exists($e, 'getHeaders') ? $e->getHeaders() : []
);
}
return parent::convertExceptionToResponse($e);
}
Answer found here: https://laracasts.com/discuss/channels/laravel/whoops-20-laravel-52

Laravel 4 PHP: 'Use' statement with both local files and package files

I am trying to include a custom defined validation file that is local to my system and wish to use it with 'package' files from an application I downloaded online. The purpose is so that I can have my own custom validators since I made modifications to this application.
I keep getting the error -> 'Class 'Models\Validators\Photo' not found'
Controller:
use JeroenG\LaravelPhotoGallery\Controllers\AlbumsController; /* From Package */
use JeroenG\LaravelPhotoGallery\Controllers\PhotosController; /* From Package */
use JeroenG\LaravelPhotoGallery\Models\Album; /* From Package */
use JeroenG\LaravelPhotoGallery\Models\Photo; /* From Package */
use Models\Validators as Validators; /* Custom local file */
class EditPhotosController extends PhotosController {
public function __construct()
{
parent::__construct();
}
public function update($albumId, $photoId)
{
$input = \Input::except('_method');
$validation = new Validators\Photo($input); // Here's where error occurs
/* Validation check and update code etc. */
}
}
}
Photo.php -> File path: Models\Validators\Photo.php
namespace Models\Validators;
class Photo extends Validator {
public static $rules = array(
'album_id' => 'required',
'photo_name' => 'required',
'photo_description' => 'max:255',
);
}
Is this just a simple namespacing issue?
The most likely problem is that composer doesn't add file Models/Validators/Photo.php to the autoload index. Make sure you have provided correct path for your files in composer.json.
Try running
composer dump-autoload
to regenerate the autoload files.

Categories