Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extend Request class in Laravel 5

I'm new to Laravel (only experienced Laravel 5, so no legacy hang up here)

I'd like to know how to extend the core Request class. In addition to how to extend it, i'd like to know if it's a wise design decision to do so.

I've read through the documentation extensively (especially with regards to registering service providers and the manner in which it provides Facades access to entries within the dependency container) - but I can see (and find) no way to replace the \Illuminate\Http\Request instance with my own

like image 428
ninjapenguin Avatar asked May 10 '15 19:05

ninjapenguin


4 Answers

Here is Official Document: Request Lifecycle

Content of app/Http/CustomRequest.php

<?php namespace App\Http;

use Illuminate\Http\Request as BaseRequest;

class CustomRequest extends BaseRequest {
    // coding
}

add this line to public/index.php

$app->alias('request', 'App\Http\CustomRequest');

after

app = require_once __DIR__.'/../bootstrap/app.php';

change the code at public/index.php

Illuminate\Http\Request::capture()

to

App\Http\CustomRequest::capture()
like image 94
g4li Avatar answered Oct 19 '22 20:10

g4li


I was working on the same issue today and I think it's worth mention that you may just change

Illuminate\Http\Request::capture()

to

App\Http\CustomRequest::capture()

without adding line

$app->alias('request', 'App\Http\CustomRequest');

because inside capture() method laravel actually binds provided class to service container with 'request' as a key

like image 35
Egor Avatar answered Oct 19 '22 20:10

Egor


I guess you will have to extend also RequestForm. I use trait to avoid code duplication. Code below is relevant for Laravel 5.3.

app/Http/ExtendRequestTrait.php

<?php
namespace App\Http\ExtendRequestTrait;

trait ExtendRequestTrait {
  methodFoo(){}
  methodBar(){}
}

app/Http/Request.php

<?php
namespace App\Http;
use Illuminate\Http\Request as BaseRequest;

class Request extend BasicRequest {
  use ExtendRequestTrait;
}

app/Http/FormRequest.php

<?php
namespace App\Http;
use Illuminate\Foundation\Http\FormRequest as BaseFormRequest;

class FormRequest extend BasicFormRequest {
  use ExtendRequestTrait;
}

For phpunit test working you will have to override call method to make it using right Request class here Request::create.

test/TestCase.php

<?php
use App\Http\Request;

abstract class TestCase extends Illuminate\Foundation\Testing\TestCase{

   // just copy Illuminate\Foundation\Testing\TestCase `call` method 
   // and set right Request class
   public function call($method, $uri, $parameters = [], $cookies = [], $files = [], $server = [], $content = null)
    {
        $kernel = $this->app->make('Illuminate\Contracts\Http\Kernel');

        $this->currentUri = $this->prepareUrlForRequest($uri);

        $this->resetPageContext();

        $request = Request::create(
            $this->currentUri, $method, $parameters,
            $cookies, $files, 
            array_replace($this->serverVariables, $server), 
            $content
        );

        $response = $kernel->handle($request);

        $kernel->terminate($request, $response);

        return $this->response = $response;
    }

}

and don't forget to switch Illuminate\Http\Request::capture() to App\Http\Request::capture() in public/index.php file and to add $app->alias('request', 'App\Http\Request'); after or inside $app = require_once __DIR__.'/../bootstrap/app.php';

like image 3
Александр Барсуков Avatar answered Oct 19 '22 18:10

Александр Барсуков


Yerkes answer inspired me to write a custom class, for use with pagination, but only on specific requests

<?php

namespace App\Http\Requests;

use Illuminate\Http\Request;

class PaginatedRequest extends Request
{
    public function page(): int
    {
        return max(1, (int) ($this['page'] ?? 1));
    }

    public function perPage(): int
    {
        $perPage = (int) ($this['per_page'] ?? 100);
        return max(1, min($perPage, 500));
    }

    public function offset(): int
    {
        return ($this->page() - 1) * $this->perPage();
    }
}

I then also had to register a new ServiceProvider in /config/app.php, which looks like

<?php

namespace App\Providers;

use App\Http\Requests\PaginatedRequest;
use Illuminate\Support\ServiceProvider;

class PaginatedRequestServiceProvider extends ServiceProvider
{
    public function boot()
    {
        $this->app->resolving(PaginatedRequest::class, function ($request, $app) {
            PaginatedRequest::createFrom($app['request'], $request);
        });
    }
}

Now I can simply inject the PaginatedRequest in my controller methods only when I need it

<?php

namespace App\Http\Controllers;

use App\Http\Requests\PaginatedRequest;

class MyController
{
    public function __invoke(PaginatedRequest $request)
    {
        $request->page();
        // ...
    }
}
like image 3
Pete McFarlane Avatar answered Oct 19 '22 18:10

Pete McFarlane