Laravel 11 for Beginners: Error Handling

Arlind Musliu Portrait
Arlind Musliu

January 17, 2024 · 4 min read

Laravel Blogpost Image

2024 UPDATE - LARAVEL 11

We're excited to announce that we have updated all of our blog post examples to reflect the new Laravel 11 version! Our previous examples were based on Laravel 10, but with the release of Laravel 11, we wanted to ensure that our readers have access to the most up-to-date information and examples.

Enhanced UX with better Error Handling

Every developer knows that encountering errors is an inevitable part of building an application. However, how you handle these errors can make a significant difference in the user experience. In Laravel, error handling is built to be simple yet robust, providing you with tools to manage exceptions gracefully.

Understanding Laravel's Error Handling

Laravel comes equipped with a built-in error-handling mechanism that automatically logs errors and displays them in a user-friendly manner. The core of this system is the Exception class, which Laravel uses to handle exceptions throughout your application.

When an error occurs, Laravel generates an exception, which is then handled by the Handler class located in app/Exceptions/Handler.php. This class contains two methods: report and render.

The Report Method

The report method is used to log exceptions or send them to an external service like Sentry. By default, Laravel logs errors in the storage/logs directory. If you need to customize the logging behavior, you can modify this method.

The Render Method

The render method is responsible for converting exceptions into HTTP responses that are sent back to the browser. Laravel includes a set of predefined exceptions that result in the corresponding HTTP status codes, such as NotFoundHttpException for 404 errors.

Customizing Error Pages

Laravel allows you to easily customize error pages for different HTTP status codes. For example, if you want to create a custom 404 Not Found page, you can create a 404.blade.php file in the resources/views/errors directory.

@extends('layouts.app')

@section('title', 'Page Not Found')

@section('content')
    <h1>Oops! The page you are looking for can't be found.</h1>
    <p>Return to the <a href="{{ url('/') }}">homepage</a>.</p>
@endsection

With this custom view, users will see a friendly error message instead of the default error page when they try to access a non-existent route on your blog.

Handling Form Validation Errors

Laravel makes handling form validation errors straightforward. When using form requests, as discussed in a previous article, Laravel automatically redirects the user back to the form with error messages if the validation fails.

In your Blade templates, you can display these errors using the $errors variable provided by Laravel:

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

Logging Exceptions in the Controller

In addition to displaying errors, you may want to log them for debugging purposes. Laravel allows you to configure logging channels in config/logging.php. You can log errors to files, the system error log, external services, and more.

Within your PostController, you might encounter situations where you need to log an error, for instance, when an exception occurs during the creation or updating of a blog post. Laravel provides a simple way to log errors through the Log facade.

Here's an example of how you could log an error in the store method of the PostController:

<?php

namespace App\Http\Controllers;

use App\Http\Requests\StorePostRequest;
use App\Models\Post;
use Illuminate\Support\Facades\Log;

class PostController extends Controller
{
    public function store(StorePostRequest $request)
    {
        try {
            $validatedData = $request->validated();
            
            $post = Post::create($validatedData);
            
            // other stuff
            
            // Redirect to the new post with a success message
            return redirect()->route('posts.show', $post)
							 ->with('success', 'Post created successfully!');
        } catch (\Exception $e) {
            
			// Log the error
            Log::error('Post creation failed', [
                'error' => $e->getMessage(),
                'user_id' => $request->user()->id,
            ]);

            // Redirect back with an error message
            return back()->withInput()
						 ->withErrors(['msg' => 'Post creation failed']);
        }
    }
}

In this example, we wrap our post-creation logic in a try-catch block. If an exception occurs while attempting to create a new post, we catch it and use the Log facade to record the error. The Log::error method takes two parameters: the error message and an array of contextual data that can help with debugging.

The contextual data array includes the exception message and any other relevant information, such as the user's ID. This data is beneficial when reviewing the logs, as it provides more insight into what might have caused the error.

After logging the error, we redirect the user back to the previous page with the input data they provided (back()->withInput()) and include an error message to inform them that the post creation failed.

Remember to import the Log facade at the top of your controller file.

Conclusion

Effective error handling is a vital part of any web application, and Laravel provides you with the tools to do it well. From logging exceptions to displaying user-friendly error pages, Laravel's error-handling system is both powerful and flexible.

Upcoming Articles in the Series

  1. Laravel for Beginners: Using Queues

  2. Laravel for Beginners: Sending Emails

  3. Laravel for Beginners: Localization and Languages


Bring Your Ideas to Life 🚀

If you need help with a Laravel project let's get in touch.

Lucky Media is proud to be recognized as a Top Laravel Development Agency

Arlind Musliu Portrait
Arlind Musliu

Cofounder and CFO of Lucky Media

Technologies:

Laravel
Heading Pattern

Related Posts

Stay up to date

Be updated with all news, products and tips we share!