Laravel 5: Custom abort() message
Asked Answered
G

10

27

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.

Gig answered 26/7, 2016 at 9:3 Comment(2)
Possible duplicate of Pass a custom message (or any other data) to Laravel 404.blade.phpTransform
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()).Haphazard
L
39

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() }}
Lilia answered 5/8, 2017 at 6:51 Comment(3)
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?Fix
@Fix If the message contains HTML code (like <br>), use {!! !!} syntax instead of {{ }} to display unescaped content.Lilia
in laravel 5.7 @section('message', __( $exception->getMessage() ? $exception->getMessage() :'Whoops, something went wrong on our servers.'))Puckett
E
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) );
Easternmost answered 12/8, 2019 at 15:21 Comment(1)
Shorter if we use an array message abort( response(['message' => 'Unauthorized'], 401) ); for JSON.Endicott
T
11

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);
Tourcoing answered 27/7, 2016 at 11:30 Comment(2)
However, return would continue with the execution of the caller. With abort, I don't want carry on with any business logic.Isooctane
Oh, and this doesn't work either, at least in my app it didn't. response('', 400)->json('some message') still returned HTML page.Isooctane
F
1

Should be able to use the following in the template:

{{ $exception->getMessage() }}
Fatality answered 17/1, 2017 at 12:32 Comment(0)
C
0

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()]);
}
Columella answered 26/7, 2016 at 9:22 Comment(4)
I tried it, but then it won't get to the .catch in the browser.Gig
i didn't get you "it won't get to the .catch in the browser" meansColumella
Using Promise: promise.then(this._thenMethod).catch(this._defaultCatcher);Gig
Okay. I'm not sure but try send response as json like this return response()->json(['message' => $e->getMessage()]);Columella
N
0

All the other answers require modification to blade files which the OP specifically implied he does not want to do.

The only built-in blade that is able to display a custom message is 403.blade.php. This is the case as of Laravel 10.

So to abort with a custom message that can be seen by remote end, e.g. cURL etc, use this:

abort(403, 'Your custom message');
Nasty answered 15/5 at 16:12 Comment(0)
T
-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

Tenant answered 26/7, 2016 at 9:36 Comment(1)
I should add that I'm talking about an $.ajax call and not browser redirect.Gig
G
-1

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;
}
Gig answered 26/7, 2016 at 11:29 Comment(0)
T
-1

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) );
Tine answered 16/5, 2022 at 22:23 Comment(3)
not working with laravel 9Abbasid
I am currently using it in Laravel 9 and it works. can you share what error you are getting when you tried it .Tine
use Illuminate\Support\Facades\Response;Populous
R
-1

In api.php file, add this

 Route::fallback(function () {
  return abort(401,"User can't perform this action.");
 });
Raychel answered 16/5, 2023 at 10:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.