Error from Laravel to AJAX fileupload - ajax

I have an AJAX upload that sends the uploaded file (image in this case) to a function in Laravel 5.3. There I have this validation check in said function:
...
$validator = Validator::make($request->all(), [
'image' => 'image|mimes:jpeg,png,jpg|max:512',
]);
// If validator fails return this error to AJAX
if($validator->fails()) {
return response()->json('error', 422);
}
...
How would I be able to set the response()->json('error', 422) with a custom error. Now I only get an error that the file upload has failed. I would like more feedback then that.
For example: let the user know his file is to large or let the user know his extension is not allowed.
Thanks

You can get error messages from validator and send it to response, here is example.
if ($validator->fails()) {
return response()->json([
'success' => false,
'error' => $validator->getMessageBag()->toArray()
], 422);
}

Related

How to remove console error 422 (Unprocessable Content)

I write validation for email in my controller
public function store(Request $request)
{
/*
* validate request
*/
$request->validate([
'email' => ['required', 'unique:leads', 'email'],
]);
return response()->json([],422);
if (\App\Models\Lead::where(['email' => $request->get('email')])->count() > 0) {
// user found
return response()->json([ 'data' => [
'message' => 'lindirizzo email è già registrato'
]], 200);
}
else {
// Register the new user or whatever.
$client = \App\Models\Lead::create(['email' => $request->get('email'),]);
return response()->json([ 'data' => [
'message' => 'Registrato con successo!'
]], 201);
}
}
And when i write the same email in front i get error POST http://127.0.0.1:8000/api/register/leads 422 (Unprocessable Content)
My network respons its ok,
{"message":"validation.unique","errors":{"email":["validation.unique"]}}
But i dont want to show error in console
This line of code is unnecessary.
// ...
return response()->json([],422);
// ...
Remove it.
Writing The Validation Logic
... if the validation fails, the proper response will automatically be
generated. If the validation passes, our controller will continue
executing normally.
Addendum
The block of code below is unnecessary as well since the validation rule 'unique:leads' is sufficient:
// ...
if (\App\Models\Lead::where(['email' => $request->get('email')])->count() > 0) {
// user found
return response()->json([ 'data' => [
'message' => 'lindirizzo email è già registrato'
]], 200);
}
// ...
Remove it as well!
If you wish to have a custom message for the "unique email" validation, add it as the second parameter of the ->validate(...) method:
$request->validate([
'email' => ['required', 'unique:leads', 'email'],
], [
'email.unique' => 'lindirizzo email è già registrato'
]);
First, you need to check is there any email is available already or not in the table.
If you found any count of that email then simply ignore creating a record else you can add that email with a new entry inside the database.
if (Lead::where(['email' => $request->get('email')])->count() > 0) {
return response()->json([ 'data' => [
'message' => 'User data get successfully'
]], 200);
}else{
// Add a user with new email and send json response
}
}

Why image validation accpet text file laravel postman?

I am using laravel 8 and i am uploading file from postman. I have also write validation rules for png, jpeg and jpg. But when i select any other file its also upload it.
Form data in postman is
enter image description here
and my resource file for validation is
public function rules()
{
return [
'invoice_id' => ['required', 'string'],
'invoice_date' => ['required', 'date'],
'invoice_photo_url' => ['required','image','mimes:jpeg,png,jpg'],
'invoice_net_total' => ['required','regex:/^\d*(\.\d{1,2})?$/'],
];
}
and my controller method is
public function upload(InvoiceUploadRequest $request)
{
try {
return $this->responseWithSuccess(true,"Invoice successfully uploaded!",
$this->invoiceInterface->uploadInvoice($request), Response::HTTP_OK);
}catch (\Exception $exception){
return $this->responseWithError($exception->getMessage(), Response::HTTP_OK);
}
}
how can is solve this.
thanks

Handling error thrown by resource controller's method

I' working with Laravel 5.6 and i've decided to create a resource controller to handle one of my models. Right know im trying to destroy a record from the database like this:
public function destroy(Role $role)
{
$role->delete();
return response([
'alert' => [
'type' => 'success',
'title' => 'Role destroyed!'
]
], 200);
}
It works just fine as longs as the $role exists. My problem is that i want to handle the response myself in the case that $role does not exist to do something like this:
return response([
'alert' => [
'type' => 'ups!',
'title' => 'There is no role with the provided id!'
]
], 400);
But instead, i'm getting a error like this:
"No query results for model [App\\Models\\Role]."
And that is something I don't want.
Thanks in advance!
The "No query results for model [App\\Models\\Role]." is the standard response message for a ModelNotFound exception in Laravel.
The best way to change the response for an exception like this is to use the exception handler's render function to respond with whatever message you want.
For example you could do
if ($e instanceof ModelNotFoundException) {
$response['type'] = "ups!;
$response['message'] = "Could not find what you're looking for";
$response['status'] = Response::HTTP_NOT_FOUND
}
return response()->json(['alert' => $response], $response['status']);
The alternative is to ensure that the ModelNotFound exception does not get thrown (So use ->find() rather than ->findOrFail() when querying the model)
and then using the abort helper like so if no results are returned:
abort(400, 'Role not found');
or
return response(['alert' => [
'type' => 'ups!',
'title' => 'There is no role with the provided id!']
],400);

Validate POST request Laravel?

I validate POST request like:
$validator = Validator::make($request->all(), [
"id.*" => 'required|integer'
]);
if ($validator->fails()) {
return response()->json($validator->errors, 400);
}
echo "Ok";
When I send request without parameter id it skips validation and returns echo "Ok";.
Why validation does not work?
If you expect id is array of integers you should update validation rules like this:
$validator = Validator::make($request->all(), [
"id" => 'required|array',
"id.*" => 'integer'
]);
First know when using $request->validate(); when it fail exceptions are raised!
And they are automatically handled by laravel. If it's a get, or a normal post form, then the process will redirect back to the form.
To note, when using the validate method during an AJAX request, Laravel will not generate a redirect response. Instead, Laravel generates a JSON response containing all of the validation errors. This JSON response will be sent with a 422 HTTP status code.
If you want to not have such an automatic behavior, create manually a validator, then you can check with ->fails() method, as the example show bellow. That's can be handful in a lot of situations.
<?php
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...
}
}
And there is no better then the doc itself: https://laravel.com/docs/5.7/validation
there is a lot of options, to personalize our validation process.

Laravel mimes validation rule not working for some file extensions

I'm trying to use mimes validation rule to validate uploading file.
'attachment' => 'required|file|max:1024|mimes:png,gif,jpg,txt,pdf,doc,docx,zip,rar'
It's working for some files with extensions like php but It's not working for extensions like js apk ovpn ....
Any idea?
Your messages error look like what before your validation. They should look like this
$messages = [
"attachment.required" => "error required",
"attachment.mimes" => "error mines",
];
$validator = Validator::make($data, [
'attachment' => 'required|mimes:csv,txt',
], $messages);
if ($validator->fails()) {
return redirect('/home')
->withErrors($validator)
->withInput();
} else {
// your code here
}
can you detail your file little more

Resources