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.
The standard way to validating incoming requests in Laravel is something like this:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class PostController extends Controller
{
/**
* Show the form to create a new blog post.
*
* #return Response
*/
public function create()
{
return view('post.create');
}
/**
* Store a new blog post.
*
* #param Request $request
* #return Response
*/
public function store(Request $request)
{
$validatedData = $request->validate([
'title' => 'required|unique:posts|max:255',
'body' => 'required',
]);
// The blog post is valid...
}
}
There’s nothing wrong with validating requests in controllers, But how could I write the validation logic out of the controller to keep it clean and not break Single Responsibility Principle?
You could make your own form Request.
First create a request with php artisan make:request StorePostRequest
Create your own rule in this class like:
public function rules()
{
return [
'title' => 'required|unique:posts|max:255',
'body' => 'required',
];
}
Update your controller function
public function store(StorePostRequest $request)
{
// do something
}
For more info:
https://laravel.com/docs/5.7/validation#creating-form-requests
Use the form requests provided by Laravel:
https://laravel.com/docs/5.7/validation#creating-form-requests
and make sure your controller uses the ValidatesRequests trait.
Form requests are validated before the controller actions are executed and contain validation rules and authorization logics.
I am getting a very unfriendly field name in my validation errors similar to the array notation used as name for the field's rules
EG.
$rules = [
'resource.*.name' => 'required|string|max:16'
];
// error message.
// the resource.0.name is required.
How do I rename the resource.0.name in the message to something else like name or resource name.
For more convenience you may use laravels form request validation,
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class Resource 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 [
'resource.*.name' => 'required|string|max:16'
];
}
public function messages()
{
return [
'resource.*.name' => 'The Resouce Name must match the criteria'
];
}
}
In your controller:
use App\Http\Requests\Resource;
public function store(Resource $request)
{
}
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 just want to validate API requests using laravel custom Request Handler. For this I have created a RegisterRequest, with the following content.
<?php
namespace App\Http\Requests\Api\Auth;
use App\Http\Requests\Request;
class RegisterRequest extends Request
{
/**
* 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 [
'email' => 'required'
];
}
}
And, I want it to use in AuthController as:
use App\Http\Requests\Api\Auth\RegisterRequest;
public function postRegister(RegisterRequest $request)
{
dd($request->all());
}
But, neither the validation nor the request parameters are shown in the respose.
All the routing are working fine, but the query paremeters are empty. Any help will be appriciated.
Version: Laravel: 5.1
I want to let laravel handle all request parameters and say API whether the request is made successful or with errors.
Your authorize method should return true. If it is false , RegisterRequest will return forbidden because you are not authorize to use this RegisterRequest class . So, change your authorize method from RegisterRequest to this :
public function authorize()
{
return true;
}
Edit :
If you want to reply the error message in your way you can override the response method in RegisterRequest method like this :
public function response(array $errors)
{
return \Response::json($errors);
}