Laravel 12 - How To Fetch Countries and States

Touseef Afridi
08 May 25

Laravel 12 - How To Fetch Countries and States

In this tutorial, we will discuss how to get countries and states in Laravel 12 using a ready-made package. Perfect for adding dynamic location dropdowns to your Laravel app.


If you're a video person, feel free to skip the post and check out the video instead!


Quick Overview

This guide covers how to set up country and state functionality in a Laravel 12 application using the dougsisk/laravel-country-state package. It starts with initializing a new Laravel project or using a current one, selecting MySQL as the database. Once inside the project directory, the package is added to make retrieving country and state details straightforward. The configuration is then published to allow adjustments. After that, a CountriesAndStatesController is created to fetch the required data, and a route is defined to display the results. To verify that everything is set up correctly, the Laravel development server is run and tested locally. The final part explains how to tweak the controller to load states for a chosen country, such as Germany, by using its country code, enabling dynamic location data integration for real-world applications.

Step # 1 : Create a Fresh Laravel Project or Use an Existing One.

To start, either set up a new Laravel project or work within an existing one. If Laravel is installed globally, use the following command to create a new project.
laravel new countries
Or use Composer if preferred.
composer create-project laravel/laravel --prefer-dist countries
During setup, make the following selections when prompted.
  • Starter Kit: Select None to skip installing authentication scaffolding.
  • Database: Choose MySQL for your database engine.
  • Migrations: Enter yes to generate and run the default database schema.
  • Frontend Setup: Confirm with yes to automatically run npm install and npm run build to prepare frontend assets.

This sets up a Laravel project named countries, using a minimal configuration that excludes authentication features, with MySQL as the database engine, and the default database tables automatically created during the installation process, providing a clean slate for development.

Step # 2 : Navigate to Your Laravel Project.

Launch your terminal (e.g., Git Bash) and move into the main directory of your Laravel project by running.
cd c:xampp/htdocs/countries
This command places you in the root of the countries project, enabling you to run Artisan commands and manage your Laravel files directly from the terminal.

Step # 3 : Install the Country and State Package.

To get started, run the following command to add the dougsisk/laravel-country-state package to your project.
composer require dougsisk/laravel-country-state
The dougsisk/laravel-country-state package provides a streamlined way to manage country and state data within your Laravel app. It simplifies the process of fetching and displaying location-based information, making it easier to incorporate country and state selections into your application. With built-in functions for retrieving and managing data, it greatly minimizes the complexity of handling this information.

Step # 4 : Publish the Package Configuration.

To publish the package configuration, execute the following command
php artisan vendor:publish --provider="DougSisk\CountryState\CountryStateServiceProvider" --tag="config"
Running this command will generate the configuration file for the dougsisk/laravel-country-state package, enabling you to customize its settings to fit your project's needs. This step provides flexibility in how the package handles country and state data, allowing you to fine-tune its functionality, such as modifying data formats or adding custom features, ensuring smooth integration with your application.

Step # 5 : Create a Controller.

To create the CountriesAndStatesController, run the following command.
php artisan make:controller CountriesAndStatesController
Next, open the newly created controller and update it with the following code.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use CountryState;
class CountriesAndStatesController extends Controller
{
    public function index()
    {
        // Fetches a list of countries via the CountryState package
        $countries = CountryState::getCountries();
        // Outputs the countries list for debugging purposes
        dd($countries);
    }
}
This controller provides a way to retrieve and display a list of countries using the CountryState package. The index method pulls the country data with CountryState::getCountries() and displays it via dd() for easy debugging. Once you've confirmed the data is correct, you can modify the controller to pass the data to a view and enhance functionality, such as adding filters or integrating it with other parts of your app. This lays the foundation for building dynamic, location-aware features like country-based dropdowns or region-specific content.

Step # 6 : Define a Route.

First, make sure to import the controller at the top of your web.php file.
use App\Http\Controllers\CountriesAndStatesController;
Now, add the following route.
Route::get('/', [CountriesAndStatesController::class, 'index']);
This sets up a route that links the root URL (/) to the index method inside the CountriesAndStatesController. When users visit the homepage, the controller will execute and display the list of countries retrieved from the package.

Step # 7 : Run and Test the Integration.

Launch the Laravel development server by running.
php artisan serve
Once the server is running, open your browser and visit: 127.0.0.1:8000. You should see a list of countries displayed on the page. This confirms that the route, controller, and the CountryState package are working correctly.

To fetch states for a particular country, update the index method in the CountriesAndStatesController like this, specifying the country code to retrieve the associated states and display them accordingly.
public function index()
{
    // Retrieve states for Germany (country code 'DE')
    $states = CountryState::getStates('DE');
    // Display the list of German states for debugging
    dd($states);
}
After refreshing the page, you’ll now see the states of Germany displayed, verifying that CountryState::getStates('DE') successfully returns location-specific data, confirming the controller is correctly fetching and displaying the data based on the selected country code.

This verifies that the CountryState::getStates() method correctly retrieves state data for the provided country code (DE for Germany). You can now use this information for additional features like populating state dropdowns in forms or tailoring content based on a user's selected region. Furthermore, you can expand this functionality to support dynamic filtering or integrate it with other location-based services to enhance user experience across your application.

Conclusion

By following this guide, you've successfully integrated country and state management into your Laravel 12 application using the dougsisk/laravel-country-state package. Your setup now supports retrieving and displaying location data with minimal effort, while giving you the flexibility to adjust how that data is handled through both the controller logic and the published configuration file. With all key components, controller, route, and package configuration, properly configured, your application can now serve dynamic country and state selections with ease.
For more advanced features, refer to the dougsisk/laravel-country-state documentation and explore additional options for managing countries, states, and other location-based data in your application.
Share this with friends!


"Give this post some love and slap that 💖 button as if it owes you money! 💸😄"
0

0 Comments

To engage in commentary, kindly proceed by logging in or registering