-1

I am trying to assign a middleware in __construct of a controller based on Laravel docs but it throws the follwing error:

BadMethodCallException
Method App\Http\Controllers\MyController::middlware does not exist.

that is my controller class:

<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

class MyController extends Controller
{

    public function __construct()
    {
        $this->middleware('myauth');
    }

    /** something */
    public function index()
    {
        return view('test.hi', ['name' => 'Moh']);
    }
}

And here is the middleware code:

<?php

namespace App\Http\Middleware;

use Closure;

class myauth
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {

        echo time().'<br>';
        return $next($request);
    }
}

Laravel version: 6.5.2

Where am I doing wrong?

Sam
  • 1,424
  • 13
  • 28

3 Answers3

9

Middleware can be specified within controller's constructor

public function __construct() {
    $this->middleware('auth');
}

For whole controller:

$this->middleware('auth');

Only for a particular action:

$this->middleware('auth')->only('index');

For whole controller except particular action:

$this->middleware('auth')->except('store');
Dinesh Sah
  • 211
  • 2
  • 5
4

The function is middleware, you have a typo, missing an e.

Jerodev
  • 32,252
  • 11
  • 87
  • 108
0

Firstly ask to you, Your error is middlware name is incoorect you missed e after that check the below middleware process.

Laravel Middleware - Middleware acts as a middleman between a request and a response.

Firstly goto project folder and open cmd and use this command

php artisan make:middleware MiddlewareName

after that go to App\Http\kernel.php and add one lines on $routeMiddleware

'user_block' => \App\Http\Middleware\MiddlewareName::class

After that goto your middleware In handle function (write your own middleware code)

In routes use your middleware -

Route::group(['middleware' => ['user_block']],
    function () {
Route::get('/logout', array('uses' => 'Auth\LoginController@logout'));
});

If you used this middleware in specific controller in __construct in any controller just write a line

namespace App\Http\Controllers;
use App\User;

class UserController extends Controller {

 public function __construct() {

    $this->middleware('user_block');
 }
}

If you want this middleware for just one action in the controller you can add this middleware to the route :

Route::get('/login', 'LoginController@login')->middleware('user_block');

If you used this middleware in specific controller in specific 1-2 function just write this line in __construct functiono in controller

public function __construct()
{
   $this->middleware('user_block')->only(['login','register']);
}
Shubham Gupta
  • 291
  • 3
  • 10