Logo

dev-resources.site

for different kinds of informations.

Roll your own Request object in Laravel

Published at
12/31/2020
Categories
php
laravel
request
Author
titasgailius
Categories
3 categories in total
php
open
laravel
open
request
open
Author
12 person written this
titasgailius
open
Roll your own Request object in Laravel

There are multiple ways to extend or modify the Request object in Laravel. I'd like to show you a method, which in my opinion is the cleanest one.


Macro

You may already know about the macro method. It's the most obvious way to introduce new methods to the Request object but it has some downsides.

Request::macro('project', function () {
    return $this->user();
});
Enter fullscreen mode Exit fullscreen mode

This solution is simple but it has some flaws:

โ€ข You cannot override or change existing methods.
โ€ข It's not obvious where these new methods are coming from.
โ€ข No IDE autocompletion.


Custom Request Object

I like creating my own Request object.

<?php

namespace App\Http;

use Illuminate\Http\Request as LaravelRequest;

class Request extends LaravelRequest
{
    /**
     * Get the team making the request.
     *
     * @param  string|null  $guard
     * @return mixed
     */
    public function team($guard = null)
    {
        return $this->user($guard);
    }
}
Enter fullscreen mode Exit fullscreen mode

It's simple, clean and straightforward. Much better than introducing new methods via "macros".


Now, we need to instruct Laravel to use this new custom class as a base.

Simply override the handle method in our App\Http\Kernel class to use your custom Request object.

<?php

namespace App\Http;

use App\Http\Request;
use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
    // ...

    /**
     * Handle an incoming HTTP request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function handle($request)
    {
        return parent::handle(
            Request::createFrom($request)
        );
    }
}
Enter fullscreen mode Exit fullscreen mode

... and finally, alias your new App\Http\Request class so the container always returns the same instance.

$this->app->alias('request', Request::class);
Enter fullscreen mode Exit fullscreen mode

Happy Coding!

request Article's
30 articles in total
Favicon
important status code to be known as API developer
Favicon
HTTP Headers in API
Favicon
Mastering API Request Chaining: Essential Techniques for Developers
Favicon
Increasing API Reliability: Adding Timeouts to Node.js Fetch
Favicon
Python and APIs: how to use Python to connect and interact with APIs
Favicon
Rails Request specs with arbitrary JSON params
Favicon
Criando react hook personalizado para fazer requisiรงรตes
Favicon
HTTPS: Is it better than HTTP?
Favicon
Python: pytest accessing Flask session and request context variables.
Favicon
[HELP] Spring Boot: field is not set in request
Favicon
I'm Looking for Beta Readers
Favicon
An alternative API mocking library for frontend developers
Favicon
How to send request to join a organization in github
Favicon
Negotiating Languages with Ruby: A Journey through Linguistic Diversity
Favicon
Event-driven architecture over standard client-server aproach
Favicon
Roll your own Request object in Laravel
Favicon
Mezon wrapper for processing HTTP requests
Favicon
Preventing memory leak by handling errors and request cancellations separately in Axios
Favicon
How do you present a PR?
Favicon
How can i access the request object inside a nuxtJS module?
Favicon
React Js Axios Post Request Example Tutorial
Favicon
How to make API request from command line with CURL
Favicon
Request for Node.js has been deprecated
Favicon
NodeJS http homepage 20: request url with link menu
Favicon
Sharing the context with the model in an Express app
Favicon
A simple and useful #react component for helping with asynchronous loading/fetch data
Favicon
Feature request: @mention a user
Favicon
We want Dev.to REST API :)
Favicon
Perform small coding tasks for a reliable source of income?
Favicon
When to request data in SPA

Featured ones: