Benjamin W
Benjamin W

Reputation: 2848

Laravel detect middleware inside of blade

//blade
@if( middleware('foo') )

    pass    

@else

    not pass

@endif

//Route
Route::group(['middleware' => ['foo']], function(){

I have a page required to detect if user pass middleware and display different content in blade.

its custom login middleware, not the one from laravel original.

anyonw know how to achieve this?

Upvotes: 0

Views: 3537

Answers (2)

Sérgio Reis
Sérgio Reis

Reputation: 2523

Middleware is used to filter the HTTP requests and not what is rendered or no. You can filter a controller function to only be usable if it passes the middleware (if authenticated for example) and the controller only runs the function if it passes on the middleware. It seems to me you're trying to show different content for authenticated users, you can in blade use the Auth facade.

@if(Auth::check() )
    pass    
@else
   not pass
@endif

If you for some reason don't want to use the Auth facade, you can always use Session variables and do the validation using so.

// Midleware
Session::set('IPassedTheMiddleware','true');

//View

@if(Session::get('IPassedTheMiddleware') == 'true' )
    pass    
@else
   not pass
@endif

Read more about authentication here https://laravel.com/docs/5.4/authentication

Upvotes: 2

Sasan Farrokh
Sasan Farrokh

Reputation: 190

Simply pass a boolean variable to the controller like this :

public function handle($request, Closure $next) {
     return $next($request, true);
}

then pass the variable to the view:

public function controller(Request $request, $isMiddlewareSet) {
    return view('view',['isMiddlewareSet'=>$isMiddlewareSet]);
}

and finally use it in blade view :

@if($isMiddlewareSet) 
     //middleware is detected
@else
     //middleware is not set
@endif

Upvotes: 3

Related Questions