Laravel 10 - Get Countries and States

Touseef Afridi
05 Sep 24

Laravel 10 - Get Countries and States

In this tutorial, we’ll learn how to retrieve countries and states in Laravel 10. This is useful for dynamic forms in e-commerce, travel apps, and user registration systems


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


Quick Overview

In this guide, we’ll walk you through integrating dynamic country and state data into your Laravel application using the dougsisk/laravel-country-state package. You’ll start by creating or using an existing Laravel project, then proceed to install and configure the package. From there, you’ll build a simple controller and define a route to fetch and display country and state lists. We’ll test the setup by running the Laravel server and verifying the output directly in the browser. You’ll also update the method to retrieve states of a specific country like the U.S., confirming the integration works. This setup lays the groundwork for building location-aware features, such as dynamic dropdowns or region-based forms.

Step # 1 : Start a New Laravel Project or Use an Existing One.

You can start with a new Laravel project or use one you already have. To create a new project using the Laravel installer, run.
laravel new countries
If you prefer Composer, use the following command instead.
composer create-project laravel/laravel --prefer-dist countries
Both options will set up a fully functional Laravel project with the standard directory structure and essential files. This provides you with a clean foundation to begin development, ensuring your environment is properly configured for package installation and further customization.

Step # 2 : Access the Project Directory.

Open a terminal (e.g., Git Bash) and move into your Laravel project directory.
cd c:/xampp/htdocs/countries
Install the necessary Node modules and start the Vite development server with.
npm install && npm run dev
Leave this terminal running, and in a new terminal window or tab, navigate to the same project directory to run any additional Laravel commands as needed.

Step # 3 : Install the Country-State Package.

To use country and state data in your Laravel project, you need to install the required package using the command below.
composer require dougsisk/laravel-country-state
This package provides a ready-to-use list of countries and their corresponding states or provinces. It saves you from manually managing location data and helps in building dynamic dropdowns or location-based forms efficiently. Additionally, it simplifies integrating location-based features, such as setting country-specific fields or validating state selections. The data is well-structured and maintained, reducing the risk of errors or inconsistencies. This makes it especially useful for applications that require accurate geographic filtering, registration forms, shipping details, or administrative configurations.

Step # 4 : Publish the Package Configuration.

After installing the package, publish its configuration file so you can customize it if needed. Run the following Artisan command.
php artisan vendor:publish --provider="DougSisk\CountryState\CountryStateServiceProvider" --tag="config"
This will generate a country-state.php config file inside your Laravel project’s config directory. From here, you can fine-tune the package settings to better suit your application’s needs. You may set a default country or state, control which data sets are loaded, or even disable certain features that aren't relevant to your use case. Having this config file gives you full control and makes the integration more flexible for both simple and advanced location-based implementations.

Step # 5 : Create a Controller.

Generate a new controller to handle country and state data by running the following command.
php artisan make:controller CountriesAndStatesController
This command will create a new file at app/Http/Controllers/CountriesAndStatesController.php. Open the file 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()
    {
     $countries = CountryState::getCountries();
     dd($countries);
    }
}
This method uses the CountryState::getCountries() function from the package to fetch a complete list of available countries, which is then displayed using Laravel’s dd() (dump and die) for quick testing in the browser. Creating this controller not only verifies that the package is working correctly but also forms the foundation for handling country and state data in your app. It sets you up to build more dynamic features, like auto-loading states when a user selects a country from a dropdown.

Step #6: Define a Route

To access the controller method via the browser, first import the controller at the top of your web.php routes file.
use App\Http\Controllers\CountriesAndStatesController;
Then, define a GET route pointing to the index method.
Route::get('/', [CountriesAndStatesController::class, 'index']);
This route will trigger the controller’s method when visiting the root URL (/), allowing you to see the list of countries output from the dd() function. It acts as the entry point for testing the package integration and ensures your controller is properly connected to the front end. Later, you can update this route to return a Blade view or JSON response as needed for your application.

Step #7: Test the Country and State Data

Now it’s time to verify that everything is working as expected. Start 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 screen.

To retrieve the states of a specific country (e.g., the United States), update the index method in your controller as shown below.
public function index()
{
    $states = CountryState::getStates('US');
    dd($states);
}
After updating the method, refresh the page at 127.0.0.1:8000, and this time, you’ll see a list of U.S. states instead of countries. This allows you to confirm that the package is correctly fetching and displaying the states for the selected country. It’s a useful step for debugging and ensuring that country/state data is being handled as expected within your application. You can now use this dynamic data in forms, dropdowns, or APIs to enhance user experience and simplify location-based interactions across your app.

Conclusion

By following this guide, you’ve successfully set up and tested the dougsisk/laravel-country-state package in your Laravel application. Starting from creating or using an existing project, you installed the package, published its configuration, created a dedicated controller, and defined a route to fetch and display country and state data. You also verified the setup by retrieving a list of countries and the states of a specific country directly in your browser. This integration lays the foundation for building dynamic forms or dropdowns based on location data, making your application more interactive and user-friendly. You can now extend this functionality by populating country and state dropdowns in your views and making location-based selections seamless for your users.
For more details and advanced usage, please refer to the dougsisk/laravel-country-state documentation.
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