2

i'm new to laravel , hope someone could help me with this problem ,

i've created a request class to validate my inputs . But when the validation fails it doesn't return any error messages instead showing a 404 error.

my request class , recoverIdRequest

namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class recoverIdRequest 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 [
            'dob' => 'required',
            'email' => 'required',
        ];
    }
}

and here's my controller : testController

class testController extends Controller
{
/** 
*
* @param  \App\Http\Requests\recoverIdRequest $request
* @return Illuminate\Http\Response
*/
    public function test(recoverIdRequest $request)
    {
       
      $validated = $request->validated();
    
      
        $dob = $request->input('dob');
        $new_dob = Carbon::parse($dob)->format('Y-m-d');
        $email = $request->input('email');
   }
      
}

and this is the response in postman when the validation fails :

and this is the response in postman when the validation fails :

routes/api.php

Route::group([ 'prefix'=>'modelTesting', ], function() {
    Route::post('test/{id}' [testController::class,'test'])->middleware(['auth:api', 'scope:admin']);
}); 
5
  • whats about routes/web.php? Commented Aug 19, 2022 at 7:23
  • can you show me your route? Commented Aug 19, 2022 at 7:24
  • 1
    You should do php artisan route:list to check your routes Commented Aug 19, 2022 at 7:30
  • @Lessmore , routes are in api.php, Route::group([ 'prefix'=>'modelTesting', ], function() { Route::post('test/{id}',[testController::class,'test'])->middleware(['auth:api', 'scope:admin']); }); Commented Aug 19, 2022 at 7:31
  • Check your RouteServiceProvider, either the api prefix is missing, or the api.php is commented out or something. It can also be because of the id, if you have a model binding defined on it, and if it can't find it in database, it will return a 404. You should be able to spot any issue with php artisan route:list Commented Aug 19, 2022 at 7:45

3 Answers 3

14

Resolved

it was a problem with postman headers,i was able to fix the issue using the following headers :

Accept: application/json
X-Requested-With: XMLHttpRequest
Sign up to request clarification or add additional context in comments.

3 Comments

This works! I only use Laravel for rest api and a Vue frontend with axios.
In postman you can also set this in the pre-request setting for a collection: pm.request.headers.add({ key: 'X-Requested-With', value: 'XMLHttpRequest' });
the funniest thing is that I already faced the unexpected 404 issue (but that was another case) and I already found this solution for Postman. but that wasn't this topic :D so thank YOU too!
0

You should follow the naming convention first in all your classes.

As the information not very much clear but it should return 422 error status. It might be the problem that when validation is failed then it is trying to redirect none existence URL. Please check the type of method you are using in postman to call the api. If it not resolved please paste the request data from the postman. And the routes.php

1 Comment

route : oute::group([ 'prefix'=>'modelTesting', ], function() { Route::post('test',[testController::class,'test'])->middleware(['auth:api', 'scope:admin']); }); postman request : 127.0.0.1:8000/api/modelTesting/test
0

It does not give 404, if the validation process is not successful, validation redirects back to the previous page, in your case it gives 404 because there is no rest API and a previous page ... let's agree here it's very natural and you just have to write a small validation method for it

try it, add this method to your form request class(recoverIdRequest) and try again


    /**
     * Returns validations errors.
     *
     * @param Validator $validator
     * @throws  HttpResponseException
     */
    protected function failedValidation(Validator $validator)
    {
        // you can debug with dd() in this method 
        if ($this->wantsJson() || $this->ajax()) {
            throw new HttpResponseException(response()->json($validator->errors(), 422));
        }
        parent::failedValidation($validator);
    }


second step you should change handler

app/exceptions/Handler.php


public function render($request, Exception $e)
{
    if ($request->ajax() || $request->wantsJson())
    {
        $json = [
            'success' => false,
            'error' => [
                'code' => $e->getCode(),
                'message' => $e->getMessage(),
            ],
        ];

        return response()->json($json, 400);
    }

    return parent::render($request, $e);
}

7 Comments

He has a 404, he doesnt reach the validation step
try dd('foo') in failedValidation method ... we will solve this ,don't hesitate :)
ı know your problem just ı want from you to try dd() in failedValidation method and see it
its work? you can see output of dd() ?
sorry but I'm not the OP
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.