Im working on a Laravel Global Middleware to set Country Value in a Cookie when web visitors access the website.
For that reason I create the following function:
public function handle($request, Closure $next)
{
if(!$request->cookies->has('geo'))
{
if (!$request->cookies->has('geo') && GeoIP()->getLocation()->iso_code !== null) {
//find customer IP location
$code = strtolower(GeoIP()->getLocation()->iso_code);
// creates a cookie with iso_code value
$cookie = cookie('geo', $code, 600);
//move to page
return $next($request)->cookie($cookie);
}
else{
return response()->view('static.select-country');
//move to page
return $next($request);
}
}
if ($request->cookies->has('geo')) {
//move to page
return $next($request);
}
}
1- If cookie 'geo' is null:
2- If cookie geo is not null code: ($request->cookies->has('geo'))
(my idea for step 2 is for existing customers that already have a country (already have a cookie with that value) but they want to change manually the country in static.select-country view and avoid GeoIP detector override by loop 1.)
My problem: at this moment when customer choose manually in static.select-country view, it moves to page home:
You can create a route for that selecting country page and ignore that route in above middleware. then every one can visit that page and select own country from list and set that country code in cookie.
if ($request->is('YOUR_ROUTE_PATH')) {
return $next($request);
}