I've always used in my forms Ajax to perform CRUD, yet now I needed to make a form that posts regularly without Ajax.
The thing that is boggling me for a couple of hours is that the custom PostsRequest::class
is working nicely, yet, and here is my problem, when validation fails it echoes the JSON message. I need to capture the errors in the old fashion way, like:
@error('title')
<div class="alert alert-danger">{{ $message }}</div>
@enderror
but what I'm getting is the browser displaying:
{
"message": "Please correct the errors.",
"errors": {
"title": [
"The title must be between 15 and 16 characters."
]
}
}
The store() method in my controller:
/**
* Store a newly created resource in storage.
*
* @param \App\Http\Requests\Frontend\ReviewsRequest $request
* @param \App\Models\Review $review
*
* @return \Illuminate\Http\Response
* @since 2.2.0
*/
public function store(ReviewsRequest $request, Review $review)
{
try {
\DB::beginTransaction();
$data = $request->all();
$data['active'] = 0;
$data['approved'] = 0;
$review = $review->create($data);
// sync user reviews
$review->users()->sync(auth()->id(), $review->id);
// sync internal reviews
if($request->get('type') == 'internals') {
$review->internals()->sync(1, $review->id);
}
// sync internal reviews
if($request->get('type') == 'firm') {
$review->firms()->sync(120, $review->id);
}
\DB::commit();
return view('frontend.reviews.review_thank_you');
} catch(Exception $e) {
echo $e->getMessage();
} finally {
}
}
I've searched almost everywhere, documentation, here in StackOverflow, the web, etc, and all I find is people wanting to have a JSON response.
In my PostsRequest
class, I have set, as usual, the public function rules(){ ... }
and the public function messages( ... )
What might I be doing wrong? Thanks for any help with this quite silly question.
Well,
It's SOLVED.
After hours digging inside the code and follow every single step of the validation process, I finally found the reason behind this behavior.
In my class App\Exceptions\Handler
the render()
method has an override as follows:
/**
* Render an exception into an HTTP response.
*
* @param \Illuminate\Http\Request $request
* @param \Exception $exception
* @return \Symfony\Component\HttpFoundation\Response
*
* @throws \Exception
*/
public function render($request, Exception $exception)
{
// THIS IS WHERE THE 'BLACK MAGIC' WAS HAPPENING <----
if ($exception instanceof ValidationException){
return response()->json([
'message' =>'Please correct the errors.',
'errors' => $exception->validator->getMessageBag()], 422);
}
return parent::render($request, $exception);
}
Sometimes we have to take a break from a 20h work schedule to refresh and reset the brain...
Thanks to all who have tried to look into this question. If anyone finds himself in experiencing this kind of issue, look into your App\Exceptions\Handler::class methods' logic.