Using Laravel 5, I want to send a custom abort()
message.
For example, if the user doesn't have the required permissions for an action,
I'd like to abort(401, "User can't perform this actions")
.
Currently, when I do so, the response text is HTML page and not the message.
How can I return only the message?
Note: I don't want to pass a different view, but only the custom message.
You can wrap a response inside abort, which will stop the execution and return the response. If you want it to be JSON then add
->json();
First of all add the error message in your header file or in the page where you want to show the message like:
And in the controller, you can do this kind of stuff (e.g.):
You can redirect back with error message
According to Laravel 5.4 documentation:
https://laravel.com/docs/5.4/errors#http-exceptions
You can use
abort
helper with response text:And use
$exception->getMessage()
inresources/views/errors/500.blade.php
to display it:The answer is simply to use the response() helper method instead of abort(). Syntax as below.
You can handle all error exceptions here app/Exceptions/Handler.php Class On your requirement.
In your case just replace render function with this
Should be able to use the following in the template: