LoginSignup
5
1

More than 5 years have passed since last update.

LaravelのRequestクラスを拡張する(Not FormRequest)

Posted at
  • 初版:2018.12.18
  • laravel-5.7, php-7.2

Requestクラスをextendsしない方が良さそう。

class CustomRequest extends \Illuminate\Http\Request {} して、public/index.phpのリクエストを書き換えれば上書き出来るけど、テストの時も別途対応する必要があったり、他から元のリクエストクラスが使われてないか不安。

Request::macro()を使う。

/app/Providers/AppServiceProvider.php

class AppServiceProvider extends ServiceProvider
{
    public function boot()
    {
        $this->addMacroRequestGetClientIp();
    }

    private function addMacroRequestGetClientIp()
    {
        Request::macro('getClientIp', function () {
            foreach ([
                'HTTP_CLIENT_IP',
                'HTTP_X_FORWARDED_FOR',
                'REMOTE_ADDR'
            ] as $key) {
                // マクロ内では$thisの参照が出来る
                $ip = $this->server($key);
                if (filter_var($ip, FILTER_VALIDATE_IP)) {
                    return $ip;
                }
            }
            return '';
        });
    }
}

使うときはrequestインスタンスからメソッド名として呼び出せばいい

using_helper
class SomeController extends Controller {
    public function index() {
        request()->getClientIp();
    }
}
using_http_request
class SomeController extends Controller {
    public function index(\Illuminate\Http\Request $req) {
       $req->getClientIp();
    }
}
5
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
5
1