I'm facing a problem with custom request. I have created a request with php artisan make:request StoreNewClient.
I have configured the validations logic inside the new request file, like:
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class StoreNewClient extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return Auth::check();
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [ ...
];
}
/**
* Get the error messages for the defined validation rules.
*
* #return array
*/
public function messages()
{
return [ ...
];
}
}
In the controller, I imported the file like use App\Http\Requests\StoreNewClient; and after, In the function store() I writed:
public function store(StoreNewClient $request)
{
// Will return only validated data
$validated = $request->validated();
...
}
That what I understood from the documentation, but this give me an error: Class App\Http\Requests\StoreNewClient does not exist but exists (!!).
I already tried to clear caches and dumped the composer but didn't solved the problem. Any help?
Fount the error. In the messages(), 1 line didn't had the comma at the end and neither the app neither the composer dump-autoload, gave any error.
Related
I'm am new to laravel and i am trying to get my custom validation rules to work on my controller.
It's showing that the class does not exist.
ReflectionException thrown with message "Class App\Http\Controllers\StoreBooksRequest does not exist"
I made the request file using the artisan command.
lando artisan make:request StoreBooksRequest
this is my request file :
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class StoreBooksRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
//
'title' => 'required|unique:books|max:150',
'description' => 'required',
'isbn' => 'required|max:20'
];
}
}
and this is the controller where i am trying to get the custom request rules to work :
namespace App\Http\Controllers;
use App\Book;
use Illuminate\Http\Request;
class BooksController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
//
$books = Book::all();
return view('books.index', compact('books'));
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('books.create');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(StoreBooksRequest $request)
{
$book = new Book();
$book->title = $request->title;
$book->description = $request->description;
$book->isbn = $request->isbn;
$book->save();
}
I think the problem is with the error saying that the request file is in the Controllers folder and not in the standard Requests folder.
You have not included the namespace of your custom request's class. Add use App\Http\Requests\StoreBooksRequest; after use Illuminate\Http\Request;
You seem to be using wrong namespace for your
Class App\Http\Controllers\StoreBooksRequest
Your namespace is set to namespace App\Http\Requests; while you are calling it from controller, If you move your Class to App\Http\Requests.
Also, don't forget to import the class in your controller
use StoreBooksRequest
When you execute the php artisan make:request Myrequestname, Laravel create the file inside the App\Http\Request subdirectory, so you need to be careful to use the right namespace, another thing you always had to be carefull is about the name you use, is not the same Mycontroller than mycontroller and is worst if your server is a Linux server, because the file system make differentiation beewteen Caps.
I'm getting an error using a request class called RolesRequest in my store function in my controller, I have my controller in an Admin folder under controllers. When I change the name just to RoleRequest I still get the same error and I don't know why, I have tried to do a composer dump-autoload but that doesn't help I still get the same error. I'm using laravel 5.5.4 I think
Error Message:
Class App\Http\Requests\RolesRequest does not exist", exception: "ReflectionException"
// Controller
<?php
namespace App\Http\Controllers\Admin;
use App\Role;
use App\Http\Controllers\Controller;
use App\Http\Requests\RolesRequest;
use Illuminate\Http\Request;
class RolesController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
return view('admin.roles');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(RolesRequest $request)
{
dd('hit');
}
}
// RolesRequest Class
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class RolesRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return Auth::user()->hasRole('Admin');
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
switch($this->method())
{
case 'GET':
case 'DELETE':
{
return [];
}
case 'POST':
{
$unique = [
'name' => 'required|min:3|max:30|unique:roles,name',
];
break;
}
case 'PUT':
case 'PATCH':
{
$unique = [
'name' => 'required|min:3|max:30|unique:roles,name,'. $this->id
];
break;
}
default:break;
}
$rules = [
'display_name' => 'required|min:4|max:50',
'description' => 'required|min:10|max:100'
]
return $unique + $rules;
}
}
This is one of those fun times when there is more than 1 error happening. You are seeing the second error.
The first error is the parser failing on a syntax error in the class you are trying to use. It is trying to load that file and fails so the file is never loaded, hence the class can not be found (the second error).
Its possible the error shown here is (2/2) in the error page. Check your error log to see if it is showing an error before your "class does not exist" error that you are seeing.
The RolesRequest file has a syntax error before the return. The array definition statement doesn't have a semicolon at the end.
when I run
php artisan make:request "TestRequest"
it will create file like below :
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class TestRequest extends FormRequest // i want to change from extends 'Form Request' to extends 'MyCustomFormRequest'
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return false;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
//
];
}
}
so as you can see above is the default one, I wanted to change extends class from 'FormRequest' (this is default) to MyCustomFormRequest (this is my custom)
so how do I achieve when I run
php artisan make:request "TestRequest"
, it will automatically extends 'MyCustomFormRequest' instead of 'FormRequest' ?
First ,you need to create a new command
php artisan make:command CustomRequestMakeCommand
Copy all code from Illuminate\Foundation\Console\RequestMakeCommand to App\Console\Commands\CustomRequestMakeCommand ( Remember to change the class ,namespace,and name command also)
Secondly ,create a new sub at console folder name like "stubs/customrequest.stub" ,copy all code from request.stub (vendor/laravel/framework/src/Illuminate/Foundation/Console/stubs/request.stub) to the new one ,change the FromRequest to YourCustomFormRequest
class DummyClass extends CustomFormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return false;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
//
];
}
}
Then you can use your custom command ,you can read more about this at
https://laravel.com/docs/5.6/artisan
I make some gate like this:
Gate::define('update-post', function ($user, Post $post) {
return $user->hasAccess(['update-post']) or $user->id == $post->user_id;
});
I checked my database and it has update-post access and the user id is same as in the post. but I got:
This action is unauthorized.
errors. so am I do some mistake here? thanks.
I had a similar problem some time ago when starting to use Form Request classes for data validation. I noticed the following:
If you are using Form Requests to validate data, then first of all, check that you set properly the authorization rule that will allow it to pass. This is handled by the authorize() method that must return a boolean, that by default is set to false:
namespace App\Http\Requests\Users;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\Auth;
class UpdateUserRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
/**
* By default it returns false, change it to
* something like this if u are checking authentication
*/
return Auth::check(); // <-------
/**
* You could also use something more granular, like
* a policy rule or an admin validation like this:
* return auth()->user()->isAdmin();
*
* Or just return true if you handle the authorisation
* anywhere else:
* return true;
*/
}
public function rules()
{
// your validations...
}
}
Make sure you return true on "authorize" method
public function authorize()
{
return true;
}
For Laravel 8(also applicable to Laravel 9) go to
folder app->http->requests
choose the class file(in my case it was StoreStudentRequest.php) and in function authorize set return value to true;
public function authorize()
{
return true;
}
This problem occurred to me when I did not return true in php artisan make:request SellRequest
in functionpublic function authorize()
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class SellRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'city'=>'required',
'address'=>'required',
'type'=>'required',
'land'=>'required',
'area'=>'required'
];
}
}
<?php
namespace App\Modules\UserManagement\Request;
use Illuminate\Foundation\Http\FormRequest;
use Response;
class UserRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
public function rules()
{
$rules = [
'full_name' => 'required',
'email' => 'required|email',
'password' => 'required',
're_enter_password' => 'required'
];
return $rules;
}
}
In my case, I was not doing the right check in Gate::define(...)
So maybe double check your logic in that function
Need to authorize function return true
public function authorize()
{
return TRUE;
}
and then add auth facade or use Auth;
If you have already configured your authorize() and you still have the same problem, you may check your route/api.php You may have a error declaring the same path for 2 Controller.
Route::resource('users', UserController::class)/*authorized true*/;
Route::resource('users', User2Controller::class)/*unauthorized true*/;
add this line in your controller
**use Illuminate\Http\Request;**
instead of
use App\Http\Requests\StoreGameRequest;
and change the parameter in function as
public function store(**Request $request**)
{
$request->validate([
I want to use Form Requests to validate Model so i started by create php artisan make:request TaskRequest and after i add in TaskRequest class `
public function rules()
{
return [
'name' => 'required|min:5',
];
}
public function messages()
{
return [
'name.required' => 'A title is required',
];
}
`
and in My logic
Route::post('/tasks',function (\App\Http\Requests\TaskRequest $request){
$task = new \App\Task();
$task->name = $request->input("name");
$task->save();
return response()->json(['task was created',$task], http_response_code());
});
So when i try to add a task i get error HttpException, This action is unauthorized.,AuthorizationException ...
It was work for me without Validation. So how can i fix this issue ?
Every (self-created) request has an authorize function that determines if the user is allowed to send the request. This can be useful to check for admin privileges or similar.
In you case, you can simply return true. More information can be found in the corresponding docs
Your authorize function in your TaskRequest would look like this:
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
In your custom request class for "form request" which contains the validation logic pass return:true; instead of return:false; and then it will work like a charm.
The code will look like something as following,
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class portfolioValidate extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'title'=> 'required',
'content'=> 'required'
];
}
}
as you can use middleware to make authentication for the page which contains this form... so we don't need that authorization in the FormRequest class. So returning true will make it(validation) authorized for all cases.
I think now it is clear to everyone now.