Search code examples
laravelmiddleware

How to send session data from middleware to layout?


I have middleware:

 public function handle($request, Closure $next)
{
    if ( Auth::check() && Auth::user()->isStudent() )
    {
        return $next($request);
    }

    return redirect('/');

}

I woould like to send data to my layout with redirect, I tryed to do like this:

$errors = ['You don't have permission, this side is ony for teachers']
return redirect('/login')->with('errors', $errors);

But It doesn't work, My layout doesn't see this.

This is my layout:

<html>
<head>
</head>
<body>
 @if (session('errors'))
        <div class="alert alert-dismissible alert-danger">
            Wystąpiły następujące błędy:<br/>
            <ul>
                @foreach(session('errors') as $error)
                    <li>{!!$error!!}</li>
                @endforeach
            </ul>
        </div>
    @endif

    @yield('content')
</body>
</html>

Solution

  • Here is what you can do. use session()->flash('error','your Message')

    In your view you can do this like this

     public function handle($request, Closure $next)
    {
     if ( Auth::check() && Auth::user()->isStudent() )
    {
        return $next($request);
    }
    
    session()->flash('error','your Message')
    
    return redirect('/');
    
    }
    

    then show this session in your views.