I’m using postman to test adding a record to database. Function works when all data is sent correctly (using POST method). When I try to to send invalid data in one of the fields postman tells me that
SymfonyComponentHttpKernelExceptionMethodNotAllowedHttpException: The POST method is not supported for this route. Supported methods: GET, HEAD
Which is odd as POST definitely works when data is correct and record gets added. I am looking to get proper error message and maybe customize it.
After reading answers to similar problems, I added get method for same route as error messaging uses get as I understand? But the error persist even with get method defined.
these are my routes
Route::post('trip', 'TripController@addTrip');
Route::get('trip', 'TripController@errorTrip');
php artisan route:list shows that I have both GET and POST routes for ‘trip’, error remains
This is my function in laravel
public function addTrip(Request $request) {
$validated = $request->validate([
'date' => ['required','regex:/^(2020-08-([0-2][0-9]|30))$/'],
'user_id'=> ['required','regex:/^[0-9]*$/'],
'train_id'=> ['required','regex:/^(1|2)$/'],
'train_route_id'=> ['required', 'regex:/^(1|2)$/'],
'stop_from'=> ['required','regex:/^[1-8]$/'],
'stop_to'=> ['required','regex:/^[1-8]$/'],
]);
$data = request()->post();
DB::table('trips')->insert([
[
'user_id' => $data['user_id'],
'train_id' => $data['train_id'],
'train_route_id' => $data['train_route_id'],
'stop_from' => $data['stop_from'],
'stop_to' => $data['stop_to'],
'date' => $data['date'],
'created_at' => Carbon::now(),
'updated_at' => Carbon::now()
],
]);
}
Advertisement
Answer
Though validate also works fine but as mentioned by @CBRoe failed validation can cause automatic redirects. You can try the other method.
public function addTrip(Request $request) {
$validator = Validator::make($request->all(), [
'date' => ['required','regex:/^(2020-08-([0-2][0-9]|30))$/'],
'user_id'=> ['required','regex:/^[0-9]*$/'],
'train_id'=> ['required','regex:/^(1|2)$/'],
'train_route_id'=> ['required', 'regex:/^(1|2)$/'],
'stop_from'=> ['required','regex:/^[1-8]$/'],
'stop_to'=> ['required','regex:/^[1-8]$/'],
]);
if ($validator->fails()) {
return Redirect::back()->withErrors($validator);
}
$data = request()->post();
DB::table('trips')->insert([
['user_id' => $data['user_id'], 'train_id' => $data['train_id'], 'train_route_id' => $data['train_route_id'], 'stop_from' => $data['stop_from'], 'stop_to' => $data['stop_to'], 'date' => $data['date'], 'created_at' => Carbon::now(), 'updated_at' => Carbon::now()],
]);
As a suggestion you can also use ‘in’ validation for train_id, train_route_id. See here