Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

It would be really cool if you could add Laravel Octane support for this #193

Open
KieronWiltshire opened this issue Oct 15, 2021 · 3 comments

Comments

@KieronWiltshire
Copy link

KieronWiltshire commented Oct 15, 2021

I believe that the only reason Octane doesn't work with this is due to the way how request injection works through the service provider. See https://laravel.com/docs/8.x/octane#request-injection

Basically... the current code always leaves the user agent null.

@vodnicearv
Copy link

vodnicearv commented Mar 2, 2022

you can create middleware, and add it Kernel

app()->bind(Agent::class, function ($app) {
      return new Agent($app['request']->server->all(), $app['request']->userAgent());
});
View::share('agent', app(Agent::class));

@jangaraev
Copy link

jangaraev commented May 18, 2022

here is how I solved this:

<?php

namespace App\Providers;

use Illuminate\Foundation\Application;
use Illuminate\Support\ServiceProvider;
use Jenssegers\Agent\Agent;

class OctaneServiceProvider extends ServiceProvider
{
    private $isRunningInOctane;


    public function register()
    {
        parent::register();

        $this->registerBinding('agent', fn (Application $app) => new Agent($app['request']->server()), Agent::class);
    }

    private function registerBinding(string $name, callable $fn, string $alias): void
    {
        if ($this->runningInOctane()) {
            $this->app->bind($name, $fn, true);
        } else {
            $this->app->singleton($name, $fn);
        }

        $this->app->alias($name, $alias);
    }

    private function runningInOctane(): bool
    {
        if (is_null($this->isRunningInOctane)) {
            $this->isRunningInOctane = !$this->app->runningInConsole() && env('LARAVEL_OCTANE');
        }

        return $this->isRunningInOctane;
    }
}

I created my own service provider to handle those Octane incompatibilities of 3rd party packages in one place. In my real code I use multiple registerBinding() calls as there are several incompatible components.

Don't forget to register it in config/app.php.

Hope it helps.

@adityapryg
Copy link

adityapryg commented Dec 27, 2022

Hi @jangaraev
I've tried your suggestion but it doesn't work on me. The user agent still leaves the user agent null.🥲 Is there any things that should I write or config?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants