Angielski Uzet
Angielski Uzet

Reputation: 265

middleware for one specific method in controller in Laravel

I have middleware Auth that is in App\Http\Middleware\

In my kernel i added him like:

protected $routeMiddleware = [
        'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        'Groups' => \App\Http\Middleware\Groups::class,
        'Auth' => \App\Http\Middleware\Auth::class,
    ];

This middleware contains

<?php

namespace App\Http\Middleware;

use Closure;

class Auth
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if( !auth()->check() )
        {
            return abort(404);
        }
        return $next($request);
    }
}

And in my controller method I use

$this->middleware('Auth');

But this doesn't work at all.

And when I take my 'Auth' => \App\Http\Middleware\Auth::class, and place it into protected $middlewareGroups like \App\Http\Middleware\Auth::class, it works. But for every single page. So when I am not logged it all time abort404.

What is wrong here? I can't see, it looks fine to me.

But this middleware doesn't work for this method in which I have $this->middleware('Auth');

I am not logged in but page appears as normal.

And there should be abort404 fired cuz I am not logged

What made I wrong?

Upvotes: 18

Views: 23014

Answers (1)

Maraboc
Maraboc

Reputation: 11083

The problem that you have when you added the middleware to $middlewareGroups is explained in the doc

Out of the box, the web middleware group is automatically applied to your routes/web.php file by the RouteServiceProvider.

And if you want the middleware for just one action in the cotroller you can bind the middleware to the route :

Route::get('yourRout', 'YourController@actionX')->middleware('auth');

Or you can add it in constructor of your controller :

public function __construct()
{
    $this->middleware('auth', ['only' => ['edit']]);
}

Or you can try ( Since Laravel 5.3) :

 public function __construct()
    {
        $this->middleware('auth')->only(['edit']);
    }

Upvotes: 41

Related Questions