Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5: Custom abort() message

Tags:

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.

like image 539
Sharon Haim Pour Avatar asked Jul 26 '16 09:07

Sharon Haim Pour


2 Answers

According to Laravel 5.4 documentation:

https://laravel.com/docs/5.4/errors#http-exceptions

You can use abort helper with response text:

abort(500, 'Something went wrong'); 

And use $exception->getMessage() in resources/views/errors/500.blade.php to display it:

Error message: {{ $exception->getMessage() }} 
like image 83
Kenny Avatar answered Sep 22 '22 11:09

Kenny


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();

# Regular response abort( response('Unauthorized', 401) );  # JSON response  abort( response()->json('Unauthorized', 401) ); 
like image 40
xcitic Avatar answered Sep 18 '22 11:09

xcitic