Laravel 11 - Get Countries and States

Touseef Afridi
24 Sep 24

Laravel 11 - Get Countries and States

In this tutorial, we’ll learn how to retrieve countries and states in Laravel 11. 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

This guide walks through setting up country and state management in a Laravel application using the dougsisk/laravel-country-state package. It begins by creating a fresh Laravel project or using an existing one with minimal installation options, including MySQL for the database and Pest for testing. After accessing the project directory, the dougsisk/laravel-country-state package is installed to enable easy retrieval of country and state data. The guide continues by publishing the package configuration for customization, creating a controller (CountriesAndStatesController) to fetch country and state data, and defining a route to display the data. Finally, the Laravel development server is started, and the integration is tested by visiting a local URL, where a list of countries is displayed. The guide also shows how to modify the controller to retrieve states for a specific country (e.g., the U.S.), providing a seamless way to manage location-based data within the application.

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

If you have Laravel installed globally, you can quickly create a new project by running the following command.
laravel new countries
Alternatively, you can use Composer to create the project with the command.
composer create-project laravel/laravel --prefer-dist countries
During the setup process, select the following options when prompted.
  • Starter Kit: Choose None to install Laravel without any authentication scaffolding.
  • Testing Framework: Select Pest for a modern and streamlined testing environment.
  • Database: Set MySQL as the database to use MySQL for storage.
  • Migrations: Type yes to run migrations and automatically create the default database tables.

This will create a new Laravel project named countries. If Laravel is globally installed, the laravel new command will set up the project instantly. Otherwise, Composer will download and install Laravel. The installation is minimal, with no starter kit, and includes Pest for testing, MySQL for database configuration, and the default database migrations.

Step # 2 : Access Your Laravel Project.

Open a terminal (such as Git Bash) and navigate to the root directory of your Laravel project using the following command.
cd c:xampp/htdocs/countries
This will bring you to the root folder of your countries Laravel project, allowing you to execute commands and interact with the project files directly from the terminal.

Step # 3 : Install the Country and State Management Package.

Run the following command to install the Laravel Country and State package.
composer require dougsisk/laravel-country-state
The dougsisk/laravel-country-state package offers an efficient solution for handling country and state data within your Laravel application. It simplifies the process of accessing and managing location-based information, making it easy to integrate country and state lists into your project. With built-in methods for retrieving and displaying country and state data, it significantly reduces the effort required to manage this information.

Step # 4 : Publish the Package Configuration.

To publish the package configuration, run the following command.
php artisan vendor:publish --provider="DougSisk\CountryState\CountryStateServiceProvider" --tag="config"
Publishing the configuration file for the dougsisk/laravel-country-state package allows you to tailor its settings to better suit your project's requirements. By running the provided command, you can adjust how the package manages and retrieves country and state data. This flexibility ensures that the package integrates smoothly with your application's specific needs. Customizing the configuration file will help you fine-tune the package’s behavior, such as adjusting data formats or adding additional functionality.

Step # 5 : Create a Controller.

Run the following command to create the CountriesAndStatesController.
php artisan make:controller CountriesAndStatesController
Then, update the CountriesAndStatesController with the following code.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use CountryState;
class CountriesAndStatesController extends Controller
{
    public function index()
    {
    // Retrieves a list of countries using the CountryState package
    $countries = CountryState::getCountries();
    // Dumps and dies, displaying the list of countries for debugging purposes
    dd($countries);
    }
}
This controller allows you to fetch and display a list of countries using the CountryState package. The index method retrieves the countries with CountryState::getCountries() and outputs the data with dd() for debugging. After verifying the data, you can pass it to a view and customize the method for further functionality like filtering or integration with other parts of your application.

Step # 6 : Create a Route.

Import CountriesAndStatesController class
use App\Http\Controllers\CountriesAndStatesController;
Then, create the route.
Route::get('/', [CountriesAndStatesController::class, 'index']);
This route maps the root URL of the application to the index method in the CountriesAndStatesController, which will fetch and display the list of countries when accessed.

Step # 7 : It's time to test.

Start the Laravel development server with the following command.
php artisan serve
Next, open the browser and navigate to the following URL.
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.

Now, to take things further, we can modify the controller to fetch states for a specific country. Let’s update the index method in the CountriesAndStatesController to fetch states for the United States (or any other country). Update the method as follows.
    public function index()
    {
    // Retrieves a list of states for the specified country ('US' in this case)
    $states = CountryState::getStates('US');
    // Dumps and dies, displaying the list of states for debugging purposes
    dd($states);;
    }
After making this change, when you access the URL again, you will see a list of U.S states. The image below is for your reference.

This confirms that the CountryState::getStates() method is working as expected, retrieving data based on the specific country code (US in this case). You can now use this data for further processing, such as displaying state options in a form or filtering content based on the user's location.

Conclusion

By following this guide, you've successfully integrated country and state management into your Laravel application using the dougsisk/laravel-country-state package. Your project now allows you to easily retrieve and display a list of countries and states, with the flexibility to customize the data retrieval process through the controller and configuration settings. The integration is seamless, with all necessary components, including the controller, route, and package configuration, set up correctly. You can further enhance this functionality by customizing the controller to display additional location-based data or adding features such as city management.
For more advanced features, refer to the package 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