0
0

Laravel 学習(ミドルウェア)

Posted at

ミドルウェア

下記コマンドを実行し、ミドルウェアを作成します。

php artisan make:middleware HelloMiddleware

下記ファイルが作成されます。

\app\Http\Middleware\HelloMiddleware.php
<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class HelloMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        return $next($request);
    }
}
return $next($request);

ミドルウェアからアプリケーションへ送られるリクエストの作成をしている。
これを下記のようにするとコントローラの処理の後に実行できる。

$ response = $next($request)
何らかの処理
return $response;

image.png

下記プログラムを実行すると上図のようになります。

HelloMiddleware.php
<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class HelloMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        $data = [
          ['id'=>1, 'name'=>'a', ],
          ['id'=>2, 'name'=>'b', ],
          ['id'=>3, 'name'=>'c', ],
        ];
        $request->merge(['data'=>$data]);
        return $next($request);
    }
}
\routes\web.php
Route::get('/hello','App\Http\Controllers\HelloController@index')
->Middleware(HelloMiddleware::class);
\app\Http\Controllers\HelloController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Http\Response;

class HelloController extends Controller
{
    public function index(Request $request) {
        $data = [
            'data'=>$request->data
        ];
        return view('hello.index', $data);
    }
}
\resources\views\hello\index.blade.php
@extends('layouts.helloapp')

@section('title', 'タイトル')

@section('menubar')
   @parent
   showの値
   <li></li>
@endsection

@section('content')
   <p>コンテンツ</p>
   <p>何か記述する</p>
   
   <ul>
      @foreach($data as $item)
         <li>{{$item['id']}}: {{$item['name']}}</li>
      @endforeach
   </ul>

@endsection

@section('footer')
   <h2>フッター</h2>
   <p>フッターを記載します</p>
@endsection
\resources\views\layouts\helloapp.blade.php
<html>
<head>
  <title>@yield('title')</title>
</head>
<body>
  <h1>@yield('title')</h1>
  <hr size="1">
  @section('menubar')
  <h2 class="menutitle">メニュー</h2>
  <ul>
    <li>親1</li>
    <li>@show</li>
    <li>親2</li>
  </ul>
  <hr size="1">
  <div class="content">
    @yield('content')
  </div>
  <hr size="1">
  <div class="footer">
    @yield('footer')
  </div>
</body>
</html>

グローバルミドルウェア

app.phpの「withMiddleware」にミドルウェアを追加するとグローバルミドルウェアとして使うことができ、ルーティング時に「->Middleware」が不要になる。

\bootstrap\app.php
<?php

use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;

use App\Http\Middleware\HelloMiddleware;

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        commands: __DIR__.'/../routes/console.php',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware) {
        $middleware->append(HelloMiddleware::class);
    })
    ->withExceptions(function (Exceptions $exceptions) {
        //
    })->create();
web.php
Route::get('/hello','App\Http\Controllers\HelloController@index');

ミドルウェアのグループ化

web.php
Route::get('/hello','App\Http\Controllers\HelloController@index')
->middleware('hello');
app.php
<?php

use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;

use App\Http\Middleware\HelloMiddleware;

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        commands: __DIR__.'/../routes/console.php',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware) {
        $middleware->appendToGroup('hello', [
            HelloMiddleware::class,
        ]);
    })
    ->withExceptions(function (Exceptions $exceptions) {
        //
    })->create();

helloという名前にミドルウェアを追加して呼び出している状態。

参考

0
0
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
0
0