Unveiling Laravel’s Has-Many-Through Relationship: A Step-by-Step Guide

ArjunAmrutiya
3 min readOct 25, 2023

Introduction:
Laravel, a popular PHP framework in the realm of web development, is admired for its elegant syntax and rich feature set. One of its notable strengths is the Eloquent ORM, a robust tool for database management, including handling relationships between database tables. In this tutorial, we’ll dive into the world of has-many-through relationships in Laravel.

This guide will walk you through the process of setting up, managing, and fully utilizing has-many-through relationships in Laravel. Whether you’re new to Laravel or looking to deepen your understanding of the Eloquent ORM, this step-by-step tutorial will provide you with a comprehensive grasp of has-many-through relationships.

Prerequisites

Before we dive in, make sure you meet the following prerequisites:

  • A basic understanding of PHP
  • Composer installed on your system
  • Laravel installed (if not, refer to Laravel’s official documentation for guidance)

Step 1: Setting Up the Laravel Project

If you haven’t already, create a new Laravel project using the following command:

composer create-project --prefer-dist laravel/laravel has-many-through-relationship

Navigate to your project directory

cd has-many-through-relationship

Step 2: Database Configuration

Now, let’s set up a database and configure it in your .env file. Open the .env file and set the DB_DATABASE, DB_USERNAME, and DB_PASSWORD variables to match your database settings.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your_database_name
DB_USERNAME=your_database_username
DB_PASSWORD=your_database_password

After configuring your database, execute the migrations to create the necessary tables:

php artisan migrate

Step 3: Creating Models

Next, we’ll create three models to represent a has-many-through relationship. For this example, let’s work with a Country model, a State model, and a City model.

php artisan make:model Country
php artisan make:model State
php artisan make:model City

Step 4: Define the Relationship

In your Country model, establish the has-many-through relationship with the City model through the State model by creating a cities method. This method uses the hasManyThrough Eloquent relationship:

// app/Country.php
public function cities()
{
return $this->hasManyThrough(City::class, State::class);
}

In your State model, define the relationship to the City model by creating a cities method. This method uses the hasMany Eloquent relationship:

// app/State.php
public function cities()
{
return $this->hasMany(City::class);
}

Step 5: Creating and Retrieving Records

You can now create and retrieve records using the has-many-through relationship. Here’s how you can associate cities with countries:

// Create a country
$country = new Country(['name' => 'United States']);
$country->save();

// Create a state within the country
$state = new State(['name' => 'California']);
$country->states()->save($state);

// Add cities to the state
$state->cities()->createMany([
['name' => 'Los Angeles'],
['name' => 'San Francisco'],
]);

To retrieve the cities within a country:

$country = Country::find(1);
$cities = $country->cities;

Step 6: Updating and Deleting Records

Updating and deleting related records is straightforward. To update a city’s name:

$city = City::find(1);
$city->update(['name' => 'New York']);

To delete a city:

$city = City::find(1);
$city->delete();

Conclusion

In this tutorial, we’ve explored the creation and management of has-many-through relationships in Laravel. Understanding how to use Eloquent relationships is essential for building complex applications with Laravel’s powerful ORM.

By following the steps outlined in this guide, you’ve gained a solid foundation for working with has-many-through relationships in Laravel. As you continue to explore Laravel, you’ll appreciate the flexibility and convenience that Eloquent provides for handling various types of relationships in your database.

Laravel’s Eloquent ORM is a powerful tool, and mastering its features, including has-many-through relationships, will undoubtedly help you become a more efficient and effective developer. Happy coding!

Stay tuned for more Laravel tutorials and tips on our blog!

Go forth and get more out of your content. Go forth and conquer Medium! (and while you’re at it, follow me on Medium! and feel free to Subscribe)

Found this post useful? Kindly tap the 👏 button below! :)

🌟 Enjoy my blogging content? Support my work by buying me a virtual coffee on BuyMeACoffee! Your contributions help fuel insightful tech articles. Join hands in making coding more accessible and exciting for all. https://www.buymeacoffee.com/arjunamrutiya🚀

--

--

ArjunAmrutiya

👋 Hey there! I'm Arjun Amrutiya, a passionate web developer and blogger who loves all things PHP, Laravel and Vue.js. Welcome to my Medium account!