Defining a middleware for a controller, except a function in Laravel 5

1

I'm starting to work now with Laravel and realized that defining the routes directly to the controls where I can set the HTTP request type is more feasible for my application. Today I have something like this:

routes.php

Route::controller("usuario","UsuarioController");

UserController.php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
class UsuarioController extends Controller 
{
    public function __construct() 
    {
        //$this->middleware("auth");
    }
    public function getAutenticar() 
    {
        return view("Usuario/Autenticar");
    }
}

My question is the following. Is there any way I can define a manual middleware within the control where only for 2 routes would I be free of the auth middleware?

I know that if I set these routes manually in the file routes.php it works but by doing so I can not continue working using the HTTP request type definition inside my controller.

Can I in any way force my controller to accept 2 middlewares, 1 for "x" methods and another for the other methods?

    
asked by anonymous 07.08.2016 / 00:42

1 answer

4

There are other ways to set a middleware in Laravel, but I'll show you the way you need it, which is setting directly on the Controller.

Option except

To set a specific middleware for a controller, just use the except option, so you can define which methods you do not want to apply the specific middleware :

See:

$this->middleware('meu_middleware', ['except' => 'logout']);

except means "except". It means that everything passed by parameter will be ignored for that middleware.

You can also pass more than one value that will be ignored:

$this->middleware('meu_middleware', ['except' => ['logout', 'register']]);

Option only

If you just need to define where the middleware will be applied (instead of applying the exceptions), you can use the only option - means "only."

See:

 $this->middleware('meu_middleware', ['only' => ['listar', 'deletar']]);
    
07.08.2016 / 00:54