I'm trying a Laravel 5.8 request validation. I managed to return errors and display them to my view. The problem is when I try to not trigger any validation rule, for whatever reason I cannot insert records into my table.
Error
Too few arguments to function
App\Http\Requests\FieldRequest::Illuminate\Foundation\Providers{closure}(),
0 passed and exactly 1 expected
Controller
class FormController extends Controller
{
public function create()
{
return view('create');
}
public function store(FieldRequest $req)
{
$validate_data = $req->validate();
Form::create($validate_data);
return redirect()->back()->with('message', 'Success!');
}
}
FormRequest
class FieldRequest extends FormRequest
{
public function authorize()
{
return true;
}
public function rules()
{
return [
'item_name' => 'bail|required|max:255',
'sku_no' => 'required|alpha_num',
'price' => 'required|numeric',
];
}
public function messages()
{
return [
'item_name.required' => 'An Item Name is required',
'sku_no.required' => 'An SKU NO is required',
'price.required' => 'The price is required',
];
}
}
I'm expecting something to be inserted in my table. Do I need to perform the validation in my controller or not to achieve this? Thanks in advance!
public function store(FieldRequest $req)
{
$data = $req->all();
Form::create($data);
return redirect()->back()->with('message', 'Success!');
}
when you are working with form request you no need to use validate() function because your request goes in form request to validate your data then it will store records
Related
I use Laravel 8 with Resource to define routes in api.php and DestroyProductRequest in my controller:
Route::resources([
'product' => ProductController::class,
]);
In the controller:
public function destroy(DestroyProductRequest $request, Product $product) {
$product->delete();
return Response::HTTP_OK;
}
In the DestroyProductRequest.php:
public function rules() {
return [
'id' => 'required|integer|exists:products,id',
];
}
Now the key is the Route::resource convert the incoming id from the url into a model. But now how can I write the correct rule in the the rules() function?
Now it sais id: ["The id field is required."] in the error response.
Any idea?
By default Laravel does not validate the route parameters.
You have add custom logic in order to work
public function rules()
{
return [
'product' => 'required|integer|exists:products,id',
];
}
protected function validationData()
{
// Add the Route parameters to you data under validation
return array_merge($this->all(),$this->route()->parameters());
}
In a normal use case, you wouldn't validate route request. Laravel would return a 404 Not Found exception. Which is a standard and appropriate response.
Since you are using the resource, the route parameter is implicit biding key (product id), So Laravel bind the passed id as product implicitly. Change your Rules code segment as following,
public function rules() {
return [
'product' => 'required|integer|exists:products,id',
];
}
public function destroy(Product $product) {
$product->delete();
return Response::HTTP_OK;
}
If you wanna add ACL
if ($user->can('destroy', $product)) {
$product->delete();
return Response::HTTP_OK;
}
use Validator for your question
use Illuminate\Support\Facades\Validator;
public function destroy(DestroyProductRequest $request, Product $product) {
$rules = [
'id' => 'required|integer|exists:products,id',
];
$messages = [
'id.required' => 'The id field is required.',
'id.integer' => 'The id field need to be integer.',
'id.exists' => 'The id field is exists.',
];
Validator::make($request->all(), $rules, $messages)->validate();
$product->delete();
return Response::HTTP_OK;
}
Read more here: https://laravel.com/docs/8.x/validation
How do I redirect the response of Custom Request validation class to a custom page with the errors and some custom data.
The response method in the code below is not working.
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class employeeStore extends FormRequest {
public function authorize() {
return true;
}
public function rules() {
return [
'contacts' => 'bail|required|array|min:2',
'contacts.*.contact_no' => 'bail|required|regex:/[7-9][0-9]{9}/',
'contacts.*.is_preferred' => 'in:true,false',
];
}
public function messages() {
return [
'contacts.min' => 'provide at-least one alternate mobile no',
'contacts.*.contact_no.required' => 'this field is required',
'contacts.*.contact_no.regex' => 'mobile number entered is not valid',
];
}
public function response(array $errors)
{
if ($this->ajax() || $this->wantsJson())
{
return new JsonResponse($errors, 422);
}
return $this->redirector->to('profile')
->withInput($this->except($this->dontFlash))
->withErrors($errors, $this->errorBag);
}
}
I have custom validation for validating data. The custom validation doesn't have unique rule as I need to ignore this on update, therefore I am using unique rule on store() method. But this is ignored, and it only works if I change the custom validation with default validation.
It works if I have the following:
public function store(Request $request)
{
if (!$this->user instanceof Employee) {
return response()->json(['error' => 'Unauthorized'], 401);
}
$request->validate([
'name' => 'required|max:50|unique:centers'
]);
$center = Center::create($request->all());
return response()->json($center, 201);
}
But this doesn't work if I change the method signature to the following:
public function store(CustomValidation $request)
How can I use both together? I do not want to move the custom validation code inside the method as I have to repeat msyelf for update method then.
I think it will help you
use Illuminate\Contracts\Validation\Rule;
class CowbellValidationRule implements Rule
{
public function passes($attribute, $value)
{
return $value > 10;
}
public function message()
{
return ':attribute needs more cowbell!';
}
}
and
public function store()
{
// Validation message would be "song needs more cowbell!"
$this->validate(request(), [
'song' => [new CowbellValidationRule]
]);
}
or
public function store()
{
$this->validate(request(), [
'song' => [function ($attribute, $value, $fail) {
if ($value <= 10) {
$fail(':attribute needs more cowbell!');
}
}]
]);
}
What I did:
I am trying to override backpack form validation roles (update request).
UserUpdateCrudRequest.php
use App\Http\Requests\Backpack\PermissionManager\UserUpdateCrudRequest as UpdateRequest;
class UserUpdateCrudRequest extends \Backpack\PermissionManager\app\Http\Requests\UserUpdateCrudRequest
{
function __construct()
{
parent::__construct();
}
public function authorize()
{
// only allow updates if the user is logged in
return \Auth::check();
}
public function rules()
{
$rules = [
'name' => 'required',
'password' => 'confirmed',
];
return $rules;
}
}
app/Http/Controllers/Admin/Backpack/PermissionManager/UserCrudController.php
public function update(UpdateRequest $request)
{
//code
}
What I expected to happen:
The email field is mandatory on create , and not mandatory on update.
What happened:
ErrorException in UserCrudController.php line 18:
Declaration of App\Http\Controllers\Admin\Backpack\PermissionManager\UserCrudController::update() should be compatible with Backpack\PermissionManager\app\Http\Controllers\UserCrudController::update(Backpack\PermissionManager\app\Http\Requests\UserUpdateCrudRequest $request)
If I'm right,
inside UserCrudController you have,
use Backpack\PermissionManager\app\Http\Requests\UserStoreCrudRequest as StoreRequest;
use Backpack\PermissionManager\app\Http\Requests\UserUpdateCrudRequest as UpdateRequest;
If you want to make the email field not mandatory on update you have to edit the UserUpdateCrudRequest.php inside your-project/vendor/backpack/permissionmanager/src/app/Http/Requests and remove the line
'email' => 'required',
I've got a problem with error messages during validation in Laravel. I've got my custom Request:
class CreateCv extends Request
{
public function authorize()
{
return true;
}
public function rules()
{
return [
'name' => 'required',
'surname' => 'required',
];
}
public function messages()
{
return [
'name.required' => 'Fill the name!',
'surname.required' => 'Fill the surname!',
];
}
}
and then I've got a controller with create method:
class CvController extends Controller
{
public function create(Requests\CreateCv $request) {
return response()->json(['ok' => true], 200);
}
}
If everything is filled up, then it returns json response "ok" : true correctly. But when something is missing, then it returns empty msg: "msg": "". What causes this problem?
EDIT
here's the handler.php file
class Handler extends ExceptionHandler
{
protected $dontReport = [
AuthorizationException::class,
HttpException::class,
ModelNotFoundException::class,
//ValidationException::class,
];
public function report(Exception $e)
{
parent::report($e);
}
public function render($request, Exception $e)
{
return $e;
//return response()->json(['msg' => $e->getMessage()], 422);
//return parent::render($request, $e);
}
}
Can you try in your CreateCv class to extend Illuminate\Foundation\Http\FormRequest.
I encountered this recently during creating an API for a web application, every time I test the validation fields without the Accept application/json header, the errors object (I customized the ValidationException to return an errors object) is always empty.