25

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.

Sharon Haim Pour
  • 6,595
  • 12
  • 42
  • 64
  • Possible duplicate of [Pass a custom message (or any other data) to Laravel 404.blade.php](http://stackoverflow.com/questions/29163564/pass-a-custom-message-or-any-other-data-to-laravel-404-blade-php) – Tim Jul 26 '16 at 09:39
  • This behavior was fixed in Laravel 5.5. It will give back a JSON-formatted error that includes your message automatically when you call `abort($code, $message)` (provided `$request->wantsJson()`). – amphetamachine Jul 14 '22 at 19:22

9 Answers9

37

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() }}
Kenny
  • 579
  • 5
  • 8
  • This would be the correct way to do this, but how would I add 'newline' character, or line break (or bullets even better) in this message? – blamb Dec 11 '17 at 22:11
  • 2
    @blamb If the message contains HTML code (like
    ), use {!! !!} syntax instead of {{ }} to display unescaped content.
    – Kenny Dec 13 '17 at 11:40
  • 2
    in laravel 5.7 `@section('message', __( $exception->getMessage() ? $exception->getMessage() :'Whoops, something went wrong on our servers.'))` – ManojKiran A Jan 28 '19 at 09:46
19

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) );
wolmi
  • 1,659
  • 12
  • 25
xcitic
  • 191
  • 1
  • 6
12

The answer is simply to use the response() helper method instead of abort(). Syntax as below.

return response("User can't perform this action.", 401);
ShaunUK
  • 929
  • 6
  • 17
  • 4
    However, `return` would continue with the execution of the caller. With `abort`, I don't want carry on with any business logic. – Jānis Elmeris Oct 31 '17 at 18:09
  • Oh, and this doesn't work either, at least in my app it didn't. `response('', 400)->json('some message')` still returned HTML page. – Jānis Elmeris Oct 31 '17 at 18:18
1

You can handle all error exceptions here app/Exceptions/Handler.php Class On your requirement.

In your case just replace render function with this

public function render($request, Exception $e)
{
   return $e->getMessage();
   //For Json
   //return response()->json(['message' => $e->getMessage()]);
}
vijaykumar
  • 4,658
  • 6
  • 37
  • 54
1

Should be able to use the following in the template:

{{ $exception->getMessage() }}
Yidir
  • 583
  • 7
  • 12
knorthfield
  • 718
  • 7
  • 15
0

In Handler.php I altered the function:

 public function render($request, Exception $e)
{
    $response = parent::render($request, $e);

    if (method_exists($e, "getStatusCode")) {
        if ($e->getStatusCode() == 401) {
            $response->setContent($e->getMessage());
        }
    }

    return $response;
}
Sharon Haim Pour
  • 6,595
  • 12
  • 42
  • 64
0

I find this to be very clean if you are writing API's instead of using the default abort() exception error ):

 abort( response()->json(["message"=>"an error occur"], Response::HTTP_NOT_FOUND) );
Slycreator
  • 1,144
  • 11
  • 18
0

In api.php file, add this

 Route::fallback(function () {
  return abort(401,"User can't perform this action.");
 });
helvete
  • 2,455
  • 13
  • 33
  • 37
Sreejith N
  • 25
  • 5
-1

First of all add the error message in your header file or in the page where you want to show the message like:

@if($errors->has())
    @foreach ($errors->all() as $error)
        <div>{{ $error }}</div>
    @endforeach
@endif

And in the controller, you can do this kind of stuff (e.g.):

public function store(){
    if(user is not permitted to access this action) // check user permission here
    {
        return redirect()->back()->withErrors("User can't perform this actions");
    }
}

You can redirect back with error message

Ali
  • 1,408
  • 10
  • 17