Skip to content

Instantly share code, notes, and snippets.

@brentkelly
Last active March 27, 2024 11:01
Show Gist options
  • Save brentkelly/1892669d37a42379c6c020a4d487b0b9 to your computer and use it in GitHub Desktop.
Save brentkelly/1892669d37a42379c6c020a4d487b0b9 to your computer and use it in GitHub Desktop.
Customise Laravel to support forcing the asset root at runtime
<?php
namespace App\Services;
use Illuminate\Routing\UrlGenerator as BaseUrlGenerator;
class UrlGenerator extends BaseUrlGenerator
{
/**
* The original asset root so we can restore it
*/
protected ?string $originalAssetRoot = null;
/**
* Force the asset root
*/
public function forceAssetRootUrl(?string $root = null): void
{
if ($root) {
$this->originalAssetRoot = $this->assetRoot;
$this->assetRoot = $root;
} else {
$this->assetRoot = $this->originalAssetRoot;
$this->originalAssetRoot = null;
}
}
}
// THEN IN App/Providers/AppServiceProvider.php
class AppServiceProvider
{
/**
* Override the URL generator to use our extension class which allows us to
* change the base asset path when changing stores.
*
* Lifted from Illuminate\Routing\RoutingServiceProvider
*/
protected function overrideUrlGenerator(): void
{
$this->app->singleton('url', function ($app) {
$routes = $app['router']->getRoutes();
// The URL generator needs the route collection that exists on the router.
// Keep in mind this is an object, so we're passing by references here
// and all the registered routes will be available to the generator.
$app->instance('routes', $routes);
return new UrlGenerator(
$routes, $app->rebinding(
'request', $this->requestRebinder()
), $app['config']['app.asset_url']
);
});
}
/**
* Get the URL generator request rebinder.
* Lifted from Illuminate\Routing\RoutingServiceProvider
*
* @return \Closure
*/
protected function requestRebinder()
{
return function ($app, $request) {
$app['url']->setRequest($request);
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment