Laravel 5: Custom abort() message

2020-06-08 23:24发布

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.

7条回答
家丑人穷心不美
2楼-- · 2020-06-08 23:30

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) );
查看更多
我想做一个坏孩纸
3楼-- · 2020-06-08 23:36

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

查看更多
手持菜刀,她持情操
4楼-- · 2020-06-08 23: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() }}
查看更多
聊天终结者
5楼-- · 2020-06-08 23:37

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);
查看更多
迷人小祖宗
6楼-- · 2020-06-08 23:38

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()]);
}
查看更多
放荡不羁爱自由
7楼-- · 2020-06-08 23:43

Should be able to use the following in the template:

{{ $exception->getMessage() }}
查看更多
登录 后发表回答