Skip to content

Instantly share code, notes, and snippets.

@wlkns
Created October 6, 2017 12:18
Show Gist options
  • Save wlkns/3d4939606b59eb616c4a3944b976db63 to your computer and use it in GitHub Desktop.
Save wlkns/3d4939606b59eb616c4a3944b976db63 to your computer and use it in GitHub Desktop.
Laravel region selector (with cookies)
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cookie;
class RegionCookieRedirect
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param string|null $guard
* @return mixed
*/
public function handle($request, Closure $next, $guard = null)
{
if ( $request->has('set_region') )
{
if ($regionCode = $request->input('set_region', false))
{
Cookie::queue(Cookie::make('region', $regionCode));
}
else
{
Cookie::forget('region');
}
return redirect()->to($request->path);
}
return $next($request);
}
}
<?php
namespace App\Providers;
use App\Entities\Region;
use App\Entities\Site;
use Illuminate\Support\Facades\Cookie;
use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\View;
use Illuminate\Support\ServiceProvider;
class RegionServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
if ( ! app()->runningInConsole() )
{
View::share('region', $this->app->make('region'));
}
}
/**
* Register any application services.
*
* @return void
*/
public function register()
{
$this->app->singleton('region', function ($app) {
$regionCode = null;
// Determine if the region was passed as a URL parameter.
if ( Request::hasCookie('region') )
{
$regionCode = Request::cookie('region');
}
// If $regionCode is still null, its never been set, lets see if we can look it up.
if ( is_null($regionCode) )
{
// @todo IP Lookup - Determine region
}
return Region::where('code', $regionCode)->first() ?: null;
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment