9
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Laravel に Middleware を追加する

Posted at

Laravel に Middleware を追加する

1. app/Http/Middleware に追加する。

$ php artisan make:middleware Hogehoge

2. app/Http/Middleware/Hogehoge.php の中身を書く。

処理は public function handle() 内、

return $next($request);

の前に書く。

Controller に値を渡す時などは Request にマージすることで実装する。

app/Http/Middleware/Hogehoge.php
class CustomerAuth
{
    public function handle($request, Closure $next)
    {
        $hoge = 'hoge';

        // Request に混ぜて Controller へ送る
        $request->merge([
            'hoge' => $hoge,
        ]);

       return $next($request);
    }
}

Controller 側では、Request $request['hoge'] に格納されています。

3. app/Http/Kernel.php に追記する。

app/Http/Kernel.php
    protected $routeMiddleware = [
        ...,
        'hogehoge' => \App\Http\Middleware\Hogehoge::class,
    ];

4. Controller に適用する

例えばHogeController ならその __construct に書く。

app/Http/Controller/HogeController.php
    class adminController extends Controller {
        public function __construct()
        {
            $this->middleware('hogehoge');
        }

        public function view(){
            return view('view');
        }
    }

以上です。

9
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?