Skip to content

Instantly share code, notes, and snippets.

@tralves
Last active October 31, 2018 17:50
Show Gist options
  • Save tralves/ccf3597a6a08063e2325 to your computer and use it in GitHub Desktop.
Save tralves/ccf3597a6a08063e2325 to your computer and use it in GitHub Desktop.
Laravel 5 middleware that overrides pingpong-labs/modules configurations over the app's Config.
<?php
namespace App\Http\Middleware;
/**
* When using pingpong-labs/modules, you may want to override app config when the request is made
* in the context of a module.
*
* This middleware will do that. For example, if the module/MyModule/Config/config.php has the code:
*
* <?php
* return [
* 'auth' => [
* 'model' => Modules\MyModule\Entities\Access\User::class
* ]]
*
* then config('auth.model'); will return Modules\MyModule\Entities\Access\User::class
*
* The rest of the config('auth') variables will remain the same.
*
* You can use the middleware in the routes file like this:
*
* In the app/Http/Kernel.php add the line:
* protected $routeMiddleware = [
* (...)
* 'override.module.configs' => \App\Http\Middleware\OverrideModuleConfiguration::class,
*
* In the routes.php file add something like:
* Route::group(['prefix' => 'mymodule', 'middleware' => 'override.module.configs:mymodule'],
*
*/
use Closure;
use Illuminate\Support\Facades\Config;
class OverrideModuleConfiguration
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param var $moduleName
* @return mixed
*/
public function handle($request, Closure $next, $moduleName)
{
foreach (Config::get($moduleName) as $key => $configs) {
if(Config::has($key)) {
Config::set($key, array_replace_recursive(config($key),$configs));
}
if($key === 'app' && isset($configs['locale'])) {
\App::setLocale($configs['locale']);
}
}
return $next($request);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment