master

laravel/framework

Last updated at: 29/12/2023 09:25

ShareErrorsFromSession.php

TLDR

This file (ShareErrorsFromSession.php) is a middleware class that handles incoming requests and shares any error messages stored in the session with all view instances. The goal is to make it easier for views to access error messages without having to manually bind them.

Methods

None

Classes

ShareErrorsFromSession

This class is a middleware that handles incoming requests and shares error messages with all view instances. It has the following properties and methods:

  • Properties

    • $view: An instance of the ViewFactory class that manages the creation of views.
  • Methods

    • __construct(ViewFactory $view): Constructor method that initializes the $view property.
    • handle($request, Closure $next): Handles an incoming request. Shares the error messages stored in the session with all view instances and returns the result of the next middleware or route handler.
<?php

namespace Illuminate\View\Middleware;

use Closure;
use Illuminate\Contracts\View\Factory as ViewFactory;
use Illuminate\Support\ViewErrorBag;

class ShareErrorsFromSession
{
    /**
     * The view factory implementation.
     *
     * @var \Illuminate\Contracts\View\Factory
     */
    protected $view;

    /**
     * Create a new error binder instance.
     *
     * @param  \Illuminate\Contracts\View\Factory  $view
     * @return void
     */
    public function __construct(ViewFactory $view)
    {
        $this->view = $view;
    }

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        // If the current session has an "errors" variable bound to it, we will share
        // its value with all view instances so the views can easily access errors
        // without having to bind. An empty bag is set when there aren't errors.
        $this->view->share(
            'errors', $request->session()->get('errors') ?: new ViewErrorBag
        );

        // Putting the errors in the view for every view allows the developer to just
        // assume that some errors are always available, which is convenient since
        // they don't have to continually run checks for the presence of errors.

        return $next($request);
    }
}