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)
{
}
Related
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.
I have generated new form Request for the controller, but I do not know how to filter data before there will handle in the validator and so on.
Are there some native solutions in Laravel for this case?
class TestRequest 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|string",
"order" => "required|integer"
];
}
}
class TestController extends Controller
{
public function store(TestRequest $request, $chapterId)
{
// some business logic
}
}
There is some solution in Laravel 5.5 but in this example author uses
validate for filtering data from request, but I need to use filter inside TestRequest
$data = $this->validate(request(), [
//...
]); // I can't use this inside TestRequest
You can use my package: https://github.com/mikicaivosevic/laravel-filters
It's allows you to filter request values before validation...
<?php
class LoginRequest extends FormRequest {
//Filter
public function filters()
{
return [
'name' => 'lower',
'id' => 'int',
];
}
//...
}
Convert $request->name value into lowercase.
Conert $request->id value into integer.
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.
I have model like this
class test extends Model
{
public $rules = [
'title' => 'required',
'name' => 'required',
];
protected $fillable = ['title','name'];
}
And controller like this
public function store(Request $request)
{
$test=new test; /// create model object
$validator = Validator::make($request->all(), [
$test->rules
]);
if ($validator->fails()) {
return view('test')->withErrors($validator)
}
test::create($request->all());
}
Validation show error like this
The 0 field is required.
I want show this
The name field is required.
The title field is required.
I solve it
public function store(Request $request)
{
$test=new test; /// create model object
$validator = Validator::make($request->all(),$test->rules);
if ($validator->fails()) {
return view('test')->withErrors($validator)
}
test::create($request->all());
}
You are doing it the wrong way. The rules array should either be in your controller or better in a Form Request.
Let me show you a better approach:
Create a new Form Request file with php artisan make:request TestRequest.
Example TestRequest class:
namespace App\Http\Requests;
use App\Http\Requests\Request;
class TestRequest extends Request
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation messages.
*
* #return array
*/
public function messages()
{
return [
'title.required' => 'A title is required.',
'name.required' => 'The name field is required'
];
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'title' => 'required',
'name' => 'required',
];
}
}
Inject the request object into your controller method.
public function store(TestRequest $request)
{
// You don't need any validation, this is already done
test::create($request->all());
}
You could also look at validating in your model and throwing a ValidationException which will be handled as usual in your controller (with the error bag etc). E.g:
abstract class BaseModel extends Model implements ModelInterface {
protected $validationRules = [];
/**
* Validate model against rules
* #param array $rules optional array of validation rules. If not passed will validate against object's current values
* #throws ValidationException if validation fails. Used for displaying errors in view
*/
public function validate($rules=[]) {
if (empty($rules))
$rules = $this->toArray();
$validator = \Validator::make($rules,$this->validationRules);
if ($validator->fails())
throw new ValidationException($validator);
}
/**
* Attempt to validate input, if successful fill this object
* #param array $inputArray associative array of values for this object to validate against and fill this object
* #throws ValidationException if validation fails. Used for displaying errors in view
*/
public function validateAndFill($inputArray) {
// must validate input before injecting into model
$this->validate($inputArray);
$this->fill($inputArray);
}
}
Then in my Controller:
public function store(Request $request) {
$person = $this->personService->create($request->input());
return redirect()->route('people.index', $person)->with('status', $person->first_name.' has been saved');
}
Finally in my base service class
abstract class BaseResourceService {
protected $dataService;
protected $modelClassName;
/**
* Create a resource
* #param array $inputArray of key value pairs of this object to create
* #returns $object
*/
public function create($inputArray) {
try {
$arr = $inputArray;
$object = new $this->modelClassName();
$object->validateAndFill($arr);
$this->dataService->create($object);
return $object;
}
catch (Exception $exception) {
$this->handleError($exception);
}
}
If the model validates it continues as usual. If there's a validation error it goes back to the previous page with the validation errors in the flash data/error bag.
I will most probably move the $person->validate() method to my service class, however it will still work as outlined above.
You can simply make your validation by writing in Model.
In your Model File
i.e. Models\Test.php
public static $createRules = [
'name'=>'required|max:111',
'email'=>'required|email|unique:users',
];
In Controller
public function store(Request $request)
{
$request->validate(ModalName::$createRules);
$data = new ModelName();
}
Just do this. Everything will be fine.