Middleware Approach
Country-Based Currency Display in Laravel
AppServiceProvider Approach
php Block Approach
How to get data from env
Middleware Approach
Step 1: Set Up Country-Specific Configuration in Laravel
We will store the country-specific information such as country code, name, heading, language, and time zone in a centralized configuration file. This will allow easy management and scalability.
Create the Configuration File
In your Laravel application, create a new configuration file config/settings.php to hold the country data.
return [
'countries' => [
'India' => [
'code' => '+91',
'name' => 'India',
'heading' => 'Welcome to India! Explore Our Services',
'language' => 'en',
'timezone' => 'Asia/Kolkata',
],
'USA' => [
'code' => '+1',
'name' => 'USA',
'heading' => 'Welcome to the USA! Get Started Today',
'language' => 'en',
'timezone' => 'America/New_York',
],
'Japan' => [
'code' => '+81',
'name' => 'Japan',
'heading' => 'Welcome to Japan! Discover Our Features',
'language' => 'jp',
'timezone' => 'Asia/Tokyo',
],
// Add other countries...
],
];
In this file, we define an array for each country containing the country code, name, heading, language, and time zone.
Configure Dynamic Country Selection
We will allow users to select a country dynamically and display country-specific data. This can be done through an environment variable or a session.
Set Up the .env File
In your .env file, add a variable for the selected country:
SELECTED_COUNTRY=India
Create a Middleware to Set the Country
You can use a middleware to set the country dynamically based on the session or request. This ensures that the selected country is accessible globally throughout your application.
namespace App\Http\Middleware;
use Closure;
class SetCountry
{
public function handle($request, Closure $next)
{
// Retrieve the selected country and language from session or .env
$country = session('selected_country', env('SELECTED_COUNTRY', 'India'));
$language = session('selected_language', env('SELECTED_LANGUAGE', 'en'));
// Share country and language with all views
view()->share('selectedCountry', config('settings.countries.' . $country));
view()->share('selectedLanguage', config('settings.languages.' . $language));
return $next($request);
}
}
Register the Middleware
In app/Http/Kernel.php, register the middleware:
protected $middleware = [
// Other middlewares...
\App\Http\Middleware\SetCountry::class,
];
Dynamic Country-Specific Content in Blade Templates
Now that we have configured the country-specific data, let’s display it dynamically in Blade templates. We will use the selectedCountry variable shared by the middleware to display headings, country codes, languages, and time zones.
Display Country-Specific Heading
<h1>{{ $selectedCountry['heading'] }}</h1>
This will dynamically display the country-specific heading based on the selected country.
Display Country Code and Dialing Number
<p>Country Code: {{ $selectedCountry['code'] }}</p>
<p>Dial Number Format: {{ $selectedCountry['code'] }}XXXXXXXXXX</p>
This will display the country code and a generic dial number format based on the selected country.
Display Country-Specific Language
You can use the language code from the configuration to set the language for the application:
<p>Language: {{ strtoupper($selectedCountry['language']) }}</p>
This will display the language in a format like EN, JP, etc.
Display Time Zone
<p>Time Zone: {{ $selectedCountry['timezone'] }}</p>
This will show the country-specific time zone.
Handle Dynamic Time Zone Adjustments
To make the time zone dynamic based on the selected country, you can adjust the time zone in your application.
Set Time Zone in Controller
In your controller or middleware, you can use the country-specific time zone to set the time zone dynamically:
// In your middleware or controller
$timezone = $selectedCountry['timezone'];
date_default_timezone_set($timezone);
This will ensure that your application’s date and time are adjusted based on the selected country.
Create a Language Switcher (Optional)
If you want to offer multiple languages based on the selected country, you can add a language switcher.
Language Switcher in the Navbar
<select onchange="window.location.href='/set-language/' + this.value">
@foreach (config('settings.countries') as $country => $data)
<option value="{{ $country }}" {{ $selectedCountry['name'] == $country ? 'selected' : '' }}>
{{ $data['name'] }}
</option>
@endforeach
</select>
Route to Change Language
Route::get('/set-language/{country}', function ($country) {
session(['selected_country' => $country]);
return redirect()->back();
});
This route will allow users to change the country and, by extension, the language, country code, and other settings dynamically.
Country-Based Currency Display in Laravel
SELECTED_COUNTRY=India
php artisan make:middleware SetCountry
app/Http/Kernel.php
protected $middleware = [
// ... other middleware ...
\App\Http\Middleware\SetCountry::class,
];
\App\Http\Middleware\SetCountry::class,
protected $middlewareGroups = [
'web' => [
// Laravel's default middleware
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
// Add your middleware here
\App\Http\Middleware\SetCountry::class,
],
];
protected $middleware = [
// \App\Http\Middleware\TrustHosts::class,
\App\Http\Middleware\TrustProxies::class,
\Illuminate\Http\Middleware\HandleCors::class,
\App\Http\Middleware\PreventRequestsDuringMaintenance::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class, \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
];
// In app/Http/Kernel.php
'api' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Session\Middleware\StartSession::class,
// Other middleware
],
Middleware: Sharing Country Data with All Views
public function handle($request, Closure $next)
{
// Get selected country from session, or .env, or default to 'India'
$country = session('selected_country', env('SELECTED_COUNTRY', 'India'));
// Load country data from config
$countries = config('countries.countries');
if (!isset($countries[$country])) {
$country = config('countries.default', 'India');
}
$countryData = $countries[$country];
// Share country data with all views
view()->share('selectedCountry', $country);
view()->share('countryData', $countryData);
view()->share('allCountries', $countries);
return $next($request);
}
What does this do
?
Checks the session or environment for the selected country, defaults to India if not found.
Loads country data from your configuration.
Makes the current country, its data, and all countries available to every Blade view using view()->share().
config\app.php
'selected_country' => env('SELECTED_COUNTRY', 'India'),
Configuration: Country Properties
config\countries.php
<?php
return [
'countries' => [
'India' => [
'code' => '+91',
'name' => 'INDIA',
'currency' => 'INR',
'timezone' => 'Asia/Kolkata',
],
'Japan' => [
'code' => '+81',
'name' => 'Japan',
'currency' => 'JPY',
'timezone' => 'Asia/Tokyo',
],
'Canada' => [
'code' => '+1',
'name' => 'Canada',
'currency' => 'CAD',
'timezone' => 'America/Toronto',
],
'USA' => [
'code' => '+1',
'name' => 'USA',
'currency' => 'USD',
'timezone' => 'America/New_York',
],
'Colombia' => [
'code' => '+57',
'name' => 'Colombia',
'currency' => 'COP',
'timezone' => 'America/Bogota',
],
'Mexico' => [
'code' => '+52',
'name' => 'Mexico',
'currency' => 'MXN',
'timezone' => 'America/Mexico_City',
],
// Example for "Gulf Country" (using Saudi Arabia as a representative)
'Gulf Country' => [
'code' => '+966',
'name' => 'Saudi Arabia',
'currency' => 'SAR',
'timezone' => 'Asia/Riyadh',
],
// Example for "Africa" (using South Africa as a representative)
'Africa' => [
'code' => '+27',
'name' => 'South Africa',
'currency' => 'ZAR',
'timezone' => 'Africa/Johannesburg',
],
// Example for "Asia" (using Singapore as a representative)
'asia' => [
'code' => '+65',
'name' => 'asia',
'currency' => 'SGD',
'timezone' => 'Asia/Singapore',
],
'Indonesia' => [
'code' => '+62',
'name' => 'Indonesia',
'currency' => 'IDR',
'timezone' => 'Asia/Jakarta',
],
'China' => [
'code' => '+86',
'name' => 'China',
'currency' => 'CNY',
'timezone' => 'Asia/Shanghai',
],
],
'default' => 'India',
];
Controller: Preparing Data for the Dashboard
public function index()
{
// if(Auth::id() && Auth::user()->hasVerifiedEmail())
if(Auth::id())
{
$role = Auth()->user()->role;
$user = Auth::user();
$vender = auth()->user()->id;
log::info("useruser");
$selectedCountry = strtolower(config('app.selected_country', 'india'));
Log::info("Selected country", ['country' => $selectedCountry]);
$locationHelper = new LocationHelper();
$cityCountryCodeLookup = $locationHelper->handleExcludedRegions($selectedCountry) ?? [];
Log::info("Selected cityCountryCodeLookup", $cityCountryCodeLookup);
$data = addvechicles::select(
'addvechicles.*',
'addvechicles.id as vechicle_id',
'addvehical_byadmins.*',
'addvehical_byadmins.vehical as vechicle',
'shops.*'
)
->where('addvechicles.status', 'active')
->join('addvehical_byadmins', 'addvechicles.vehical_id', '=', 'addvehical_byadmins.id')
->join('shops', 'addvechicles.shop_id', '=', 'shops.id')
->orderBy('addvechicles.id', 'desc') // Change 'id' to the column you want to order by
->paginate(9)
->through(function ($vehicle) use ($cityCountryCodeLookup) {
$vehicle->currency_code = $cityCountryCodeLookup[$vehicle->city] ?? null;
return $vehicle;
});
$brand = addvehical_byadmin::select('brand')->get();
$model = addvehical_byadmin::select('model')->get();
$location = LocationHelper::processLocations();
$getuser=User::where('id',$vender)->value('number');
$user = User::where('number', $getuser)->where('status','block')->first();
if($user)
{
// Logout the user
auth()->logout();
// Destroy the session
session()->flush();
// Redirect to the 'not_approve' view
return view('not_approve');
}
return view('dashboard', compact('data','brand','model','location'));
}
else {
$selectedCountry = strtolower(config('app.selected_country', 'india'));
Log::info("Selected country", ['country' => $selectedCountry]);
$locationHelper = new LocationHelper();
$cityCountryCodeLookup = $locationHelper->handleExcludedRegions($selectedCountry) ?? [];
Log::info("Selected cityCountryCodeLookup", $cityCountryCodeLookup);
$data = addvechicles::select(
'addvechicles.*',
'addvechicles.id as vechicle_id',
'addvehical_byadmins.*',
'addvehical_byadmins.vehical as vechicle',
'shops.*'
)
->where('addvechicles.status', 'active')
->join('addvehical_byadmins', 'addvechicles.vehical_id', '=', 'addvehical_byadmins.id')
->join('shops', 'addvechicles.shop_id', '=', 'shops.id')
->orderBy('addvechicles.id', 'desc') // Change 'id' to the column you want to order by
->paginate(9)
->through(function ($vehicle) use ($cityCountryCodeLookup) {
$vehicle->currency_code = $cityCountryCodeLookup[$vehicle->city] ?? null;
return $vehicle;
});
$brand = addvehical_byadmin::select('brand')->get();
$model = addvehical_byadmin::select('model')->get();
$location = LocationHelper::processLocations();
return view('welcome',compact('data','brand','model','location'));
}
}
<?php
namespace App\Helpers;
use App\Models\addvechicles;
use App\Models\shop;
use App\Models\countries;
use Illuminate\Support\Facades\Log;
class LocationHelper
{
public function handleExcludedRegions(string $selectedCountry)
{
$excludedRegions = ['asia', 'africa', 'gulf country'];
if (!in_array($selectedCountry, $excludedRegions)) {
return null;
}
Log::info("Handling excluded region: $selectedCountry");
$cities = addvechicles::where('status', 'active')
->distinct()
->pluck('city');
$cityLocationArray = [];
foreach ($cities as $cityName) {
$location = shop::where('city', $cityName)->value('location');
$country = $this->extractCountryFromLocation($location);
$countryCode = $this->getCountryCode($country);
$currencyCode = $this->getCurrencyCode($country);
$cityLocationArray[] = [
'city' => $cityName,
'country' => $country,
'country_code' => $countryCode,
'currency_code' => $currencyCode
];
}
Log::info("City locations", $cityLocationArray);
return $this->createCityLookup($cityLocationArray);
}
private function extractCountryFromLocation(?string $location): string
{
if (!$location) return 'India';
$parts = explode(',', $location);
return trim(end($parts));
}
private function getCountryCode(string $country): ?string
{
return countries::whereRaw('LOWER(name) = ?', [strtolower($country)])
->value('country_code');
}
private function getCurrencyCode(string $country): ?string
{
return countries::whereRaw('LOWER(name) = ?', [strtolower($country)])
->value('currency_code');
}
private function createCityLookup(array $cityData): array
{
return collect($cityData)
->filter(fn($item) => !empty($item['city']))
->mapWithKeys(fn($item) => [$item['city'] => $item['currency_code']])
->toArray();
}
public static function processLocations()
{
$topCities = [
"Mumbai", "Delhi", "Bangalore", "Chennai", "Kolkata",
"Hyderabad", "Pune", "Ahmedabad", "Jaipur", "Surat"
];
$locations = shop::select('shops.city')
->distinct()
->join('addvechicles', 'addvechicles.shop_id', '=', 'shops.id')
->get()
->toArray();
return collect($locations)->partition(function($item) use ($topCities) {
return in_array(strtolower($item['city']), array_map('strtolower', $topCities));
})->flatMap(fn($collection) => $collection->all());
}
}
resources\views\auth\login.blade.php
{{ $items->price }}
@if(in_array($countryData['name'], ['Asia', 'Africa', 'Gulf Country']))
{{ $items->currency_code }}
@else
{{ $countryData['currency_symbol'] }}
@endif
/Day
</span>
AppServiceProvider Approach
Step-by-Step Explanation
The Configuration File (config/settings.php)
First, we define country-specific data in the configuration file. This file holds information such as the country code, name, heading, language, and time zone for each country.
Here’s a sample configuration for the countries:
// config/settings.php
return [
'countries' => [
'India' => [
'code' => '+91',
'name' => 'India',
'heading' => 'Welcome to India! Explore Our Services',
'language' => 'en',
'timezone' => 'Asia/Kolkata',
],
'USA' => [
'code' => '+1',
'name' => 'USA',
'heading' => 'Welcome to the USA! Get Started Today',
'language' => 'en',
'timezone' => 'America/New_York',
],
'Japan' => [
'code' => '+81',
'name' => 'Japan',
'heading' => 'Welcome to Japan! Discover Our Features',
'language' => 'jp',
'timezone' => 'Asia/Tokyo',
],
// Additional countries can be added here...
],
];
Ensure Country Data Is Available Globally
If you want this data to be available across multiple views, you can share it globally in a service provider or a middleware, as shown below:
Share Country Information in a Service Provider (Optional)
Create or update a service provider to share the selected country globally.
// app/Providers/AppServiceProvider.php
public function boot()
{
// Share the selected country and country heading globally
view()->share('selectedCountry', config('settings.countries.' . env('SELECTED_COUNTRY', 'India')));
}
Then, you can directly use $selectedCountry in any of your Blade views:
<h1>{{ $selectedCountry['heading'] }}</h1>
php Block Approach
Update the Configuration for Country-Based Headings
You can add a headings array to the config/settings.php file to define headings specific to each country.
// config/settings.php
return [
'countries' => [
'India' => [
'code' => '+91',
'name' => 'India',
'heading' => 'Welcome to India! Explore Our Services'
],
'Japan' => [
'code' => '+81',
'name' => 'Japan',
'heading' => 'Welcome to Japan! Discover Our Features'
],
'Canada' => [
'code' => '+1',
'name' => 'Canada',
'heading' => 'Welcome to Canada! Find Out More'
],
'USA' => [
'code' => '+1',
'name' => 'USA',
'heading' => 'Welcome to the USA! Get Started Today'
],
'China' => [
'code' => '+86',
'name' => 'China',
'heading' => 'Welcome to China! Join Us Now'
],
// Add more countries...
],
];
In this updated configuration, each country now has a heading key with a country-specific heading.
- Display Country-Specific Heading in Blade Template Now, in your Blade view, you can use the selected country to display the corresponding heading.
Example: Dynamic Heading Based on Selected Country
@php
// Access selected country from config and retrieve the corresponding heading
$selectedCountry = config('settings.countries.' . env('SELECTED_COUNTRY', 'India'));
@endphp
<h1>{{ $selectedCountry['heading'] }}</h1>
This will output the country-specific heading based on the SELECTED_COUNTRY value from the .env file.
- Dynamic Content Based on Selected Country You can also extend this to display other country-specific content based on the selected country.
Example: Dynamic Content Based on Selected Country
@php
// Access selected country from config
$selectedCountry = config('settings.countries.' . env('SELECTED_COUNTRY', 'India'));
@endphp
<div class="country-specific-content">
<h1>{{ $selectedCountry['heading'] }}</h1>
<p>We offer tailored services to residents of {{ $selectedCountry['name'] }}. Check out our country-specific offers!</p>
@if ($selectedCountry['name'] == 'India')
<p>Enjoy our exclusive discounts on health services across India.</p>
@elseif ($selectedCountry['name'] == 'Japan')
<p>Explore cutting-edge healthcare technology available in Japan.</p>
@elseif ($selectedCountry['name'] == 'Canada')
<p>Find premium health services available throughout Canada.</p>
@endif
</div>
How to get data from env
In env
SELECTED_COUNTRY=India
In config\app.php
'selected_country' => env('SELECTED_COUNTRY', 'India'),
In Controller
$selectedCountry = strtolower(config('app.selected_country', 'india')); // Default to 'india'
$countryData = countries::select('currency_code', 'currency_symbol')
->whereRaw('LOWER(name) = ?', [strtolower($selectedCountry)])
->first()
?->toArray();
Top comments (0)