2
1

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 3 years have passed since last update.

Codeigniter4とLaravelのミドルウェア比較

Posted at

最近はCodeIgniterを使うことが多いので
Laravel(7系)とCodeigniter4を比較しながらミドルウェアについてのメモです.
ちなみにCodeigniter4ではフィルタ-と呼びます

セッションで保持している年齢が20歳未満ならhomeにリダイレクトするというミドルウェアにします

ミドルウェアの登録

  • Laravel
app/Http/Kernel.php
protected $routeMiddleware = [
    'checkAge' => \App\Http\Middleware\CheckAge::class
]
  • Codeigniter
app/Config/Filters.php
public $aliases = [
        'checkAge' => \App\Filters\CheckAge::class
];

ミドルウェアの定義

20歳未満ならhomeへリダイレクトさせます

  • Laravel
app/Http/Middleware/CheckAge.php
<?php
namespace App\Http\Middleware;

use Closure;

class CheckAge
{
    /**
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if (session("age") < 20) {
            return redirect('home');
        }
        return $next($request);
    }
}
  • Codeigniter
app/Filters/CheckAge.php
<?php
namespace App\Filters;

use CodeIgniter\HTTP\RequestInterface;

class CheckAge implements FilterInterface
{
    public function before(RequestInterface $request)
    {
       if(session()->get('age') < 20){
         return redirect()->to('home');
      }
    }

ルートに対し年齢確認のミドルウェアを指定する

  • Laravel
routes/web.php
// 登録したミドルウェア名で検証する
Route::group(['middleware' => 'checkAge', 'prefix' => 'adult'], function() {
    Route::get('/member', 'MemberController@index');
});

  • Codeigniter
app/config/Routes.php
$routes->group('adult', ['filter' => 'checkAge'], function($routes)
{
    $routes->get('member', 'MemberController::index');
});

結論 Laravelで良くね?

2
1
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
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?