Laravel 5: Custom abort() message
Stefan Izdrail
Founder & Senior Architect · 2026-06-29
When working on web applications, ensuring the user receives a proper error message is necessary for creating an optimal user experience. The abort() method in Laravel 5 provides us with this capability. However, there are times when we want to show only a custom message instead of a full HTML page. In this blog post, we'll explore how to achieve that using the abort(401, "User can't perform this action") method without displaying the HTML page.
Note: For demonstration purposes, our example assumes you have a standard Laravel 5 installation. To ensure your environment is set up correctly, visit this blog post for guidance.
Step 1: Customize the abort() message using a closure.
The first step is to handle the request and return an appropriate view in case of any errors. This can be achieved by customizing the abort method with a closure. Here's how:
function abortIfNotHasPermission($permission) {
if (!Auth::user()->can($permission)) {
return abort(401, function () use ($permission) {
return view('errors.custom_denied', compact('permission'));
});
}
}
In this example, we created a custom abortIfNotHasPermission function that checks if the current user has access to the specified permission. If they don't have permission to perform the action, it triggers an abort with a 401 status code and renders the 'errors.custom_denied' view, passing the permission name as a compact variable for easy access inside the view.
Step 2: Create a custom error page.
Now that we have set up our custom abort handling function, let's create a dedicated error page to display the message. To do this:
1. Create a new file named 'custom_denied.blade.php' inside your application's views directory.
2. Within this file, define a simple layout with any CSS styling you require:
<!DOCTYPE html>
<html lang="en">
<head>
...
<body class="custom_denied">
...