I'm new to the whole concept of exception or error handling in laravel. Basically I have form request which, when rules aren't met, shows me 422 error in console, I want to convert that into error message in blade, but I fail.
I already tried this in Exception/Handle.php
public function render($request, Exception $exception)
{
return redirect()->back()->with('error', 'Invalid data');
// return parent::render($request, $exception);
}
My error message in blade should work with this:
@if(Session::has('error'))
<div class="alert alert-error">
{{ Session::get('error') }}
@php
Session::forget('error');
@endphp
</div>
@endif
I know that I should check error codes or instances before returning, but I just want to get this working. I can't return anything (no response at all).
One think which works is return parent::render($request, $exception);
and it thows error message in console
So more info
I don't know if it helps, but the request is made from Vue application to controller, which takes FormRequest as a parameter.
Also, I can't check error code, I tried
public function render($request, Exception $exception)
{
if ($exception->getCode() === 422) {
return response([], 356); //should throw 356 error
}
return parent::render($request, $exception); // instead this return fires and gives me 422 error
}
Vue component
my template:
<template>
<form class="form" @submit.prevent="submit()">
<input type="text" class="form-control-plaintext textField"
placeholder="Post a comment" required v-model="textField">
<button :disabled="disabled" class="btn btn-success submit" type="submit">Post</button>
<button :disabled="disabled" class="btn btn-dark submit" type="reset">Cancel</button>
</form>
</template>
my axios method:
axios
.post('/comments', {
textField: this.textField,
id: this.id,
routeName: this.routename,
})
.then(response => {
this.name = '';
this.callReload(this.id);
this.textField = '';
})
.catch(function (error) {
console.log(error)
});
You probably want to change the render
function, which I assume is from App\Exceptions\Handler.php
to return JSON
for exceptions where the request was made via JSON
.
public function render($request, $exception)
{
if ($request->isJson()) {
return response()->json(['error' => 'Error Detail'], 422);
}
}
You will also want to check the exception
type rather than simply returning a 422 status code for any JSON exception.