Laravel hasMany and belongsTo Tutorial

Laravel hasMany and belongsTo Tutorial

The Laravel hasMany and belongsTo relationships are a fantastic feature of the framework. Relationships, and specifically Eloquent Relationships, are a really popular feature of Laravel. The many to many relationships tutorial here at Vegibit is always the number one or two most popular post as you can see on the right hand side of this page. In this episode, we’re going to show some love to the hasMany and belongsTo relationships that Eloquent provides. Let’s get crackin.

The Relationships To Model

There are a ton of different ways to explore these relationships. A blog post having many comments. A comment that belongs to a user. A blog post that has many categories. You get the idea. For this example, we’ll explore the concept of a User and his or her Tweets. As you can imagine, we’ll explore the concept of a User that hasMany tweets. In addition, we’ll have a Tweet model where we can see that an individual tweet belongsTo a User. It should be a fun example.

Set Up The Database

First off, we need a database to hold our users and tweets. Dealing with users is quite easy, as it is just a single table. The tweets however are more granular. We’ll have 6 tables in total which include users, tweet_urls, tweet_tags, tweet_retweets, tweet_mentions, and tweets. Here are the migrations to make it happen. Of course we are creating this on the most excellent Laravel Homestead which we covered in this episode.

create_users_table.php source

create_tweets_table.php source

create_tweet_mentions_table.php source

create_tweet_retweets_table.php source

create_tweet_tags_table.php source

create_tweet_urls_table.php source

We Need Some Users and Tweeets

If we’re going to model the relationship between Users and Tweets, then we’re going to need some to work with! For this, we will use the most excellent package provided by thujohn. If you would like to follow along, you’ll need to configure an application in the developer tools at Twitter to do so. Rather than go into the details on how to set that up, check out the prior link, or just google around, there are a ton of examples of how to set up your application. Now, we’ll explore how to set up the Routes, Controllers, and Models to meet our goals. These following code samples may or may not contain “best practices”, it’s just a quick first stab at getting some tweets to work with!

The Twitter Login Button

We’re going to need a way to log in to Twitter. In the efforts of quickness, we’ll just hack the shipped welcome view to add a link to the login route of our application. Note that we will be sure to leave the call to an inspiring quote, so as to stay inspired at all times.

The Welcome View source

Log In To Twitter

The Routes To Use

Here is the routes file to use for this example. As you can see it is just a slightly modified version of the route file that ships with Laravel. We set up the routes for the login and callback from twitter, as well as a route that will get some tweets to work with. We’ll just put all these methods in one Twitter Controller, and call it a day.

routes.php source

The Methods of The Twitter Controller

Here is the source of our Twitter controller. If you follow it along, it should be pretty straightforward. We login to twitter, the callback is processed, Eloquent creates a new user, the user is authenticated, and finally we just redirect to the gettweets method to fetch a few tweets to work with. Read the comments if any of this is a little foreign to you. For reference, we use Eloquent to create a new User, and Laravel’s Query Builder to handle inserting all the tweets.

TwitterController.php source

The User and Tweet Models

Let’s now investigate the User and Tweet models to see how we set up the relationships for our hasMany and belongsTo scenarios. It’s so slick how this works.

User.php source

Tweet.php source

Testing Our Eloquent Relationships

With all of the leg work out of the way, we are now ready to start testing Eloquent and the relationships we had set up in our Models. This is the fun part! We have the users table and the tweets table for which we can test out all kinds of queries on. First, we’ll practice queries using each model without using any relationships. After all, it never hurts to practice. Once we have become familiar with accessing any field in the table we want, we’ll dive into using our hasMany and belongsTo relationships. Since we have two models to work with, first we’ll practice standard eloquent queries without relationships, then we will investigate the others.

Collections Vs Objects

Before we start firing off our queries, we need to make note of a quick item. Eloquent queries are going to either return a collection, or an object. This will change how you can access the data within the resulting variable this result is assigned to. Keep this in mind when working with Eloquent. Assuming we have an object to work with however, we can easily understand how the convention works. We’ll start with the ‘Hello World’ of Eloquent, finding a user by id. We’ll also list the actual queries Eloquent produces for us.

Object Example

select * from users where = 1 limit 1

In this instance, we get an object assigned to $user. This is where the magic of an object relational mapper comes in. We can now access the table’s column or field names as if they were attributes of that object. The format looks a bit like this.


Since we know the names of the columns in our table, it is so easy to access that data now. In this case we see that here:

All we have to do is simply reference the column names, it’s fantastic.

Collection Example

When you perform queries that return many results, they will come back as an Eloquent Collection of objects. Working with collections is a bit different, and is worthy of an entire episode to itself. The takeaway however is that many times you will be iterating over the collection to get data. Just like we saw an example of one User above, how about an example of a collection of tweets? That’s easy.

select * from tweets

The above code looks so simple and innocent doesn’t it? Behold! That one tiny little variable $tweets is a large Eloquent Collection of objects! Since it is a collection, you now have access to tons and tons of helper methods available to you. I wonder just how many tweets that collection contains? Easy.

The takeaway is that in an instance of a collection like this, you will usually pass the result to a view, and then loop over it like so:

This of course would echo out all 100 tweets to the browser. Now that we have the basic idea of working with an object instance and an eloquent collection when working with the database, let’s now test out our hasMany and belongsTo relationships.

User hasMany Tweets Queries

Recall that in our User Model, we had set up a relationship. We did this with a simple function like so:

Note: We did make use of the optional second and third parameters to the hasMany method. These define the foreign and local key to use for the relationship between the two tables.

The convention to figure out how to represent these things is:

This Class Name relationship Models.

Following this convention, we can say, “This User hasMany Tweets.” Easy. We can now find a user’s tweets like so:

select * from users where = ? limit 1
select * from tweets where tweets.twitter_id = 1278380054

You can use the result in your view like so:

Since we defined that tweets() function in our User model, we have that super slick access to finding a users tweets by simply adding the name of the function to the database call, i.e., User::find(1)->tweets; Also note that you have access to every single column in the remote table. So when we do this query, not only do we have access to $tweet->tweet_text like we show above, but also $tweet->id, $tweet->twitter_created_at, $tweet->twitter_id, $tweet->is_rt, and $tweet->retweet_count. So slick!

Tweet belongsTo User Queries

Recall that in our Tweet Model, we had also set up a relationship. We did this with a simple function like so:

This Class Name relationship Models.

Again following our convention, we can say that, “This Tweet belongsTo a User.” Let’s find the user of a tweet like so now:

select * from tweets where tweets.tweet_id = 573560672455237632 limit 1
select * from users where users.twitter_id = 1278380054 limit 1

This is so slick. In this query, we provide the id of a tweet, and find the user who created it. Since we are getting one single result, a user, this comes back as an object, not a collection, so we can access values right away with no need to iterate.

Laravel hasMany and belongsTo Summary

This was a great episode where we built a basic twitter application we could log into and then store some tweets. By using the power of eloquent, we were able to see how to set up relationships based on the tweets we collected. Of course we know that a user may have many tweets, and a tweet always is created by a user, but now we know how to express this in code using Laravel. Thanks for reading!

Leave a Reply