Rebuild Twitter with Laravel – Upgrade to 5.4, Post Tweet, Link Preview, URL Shortener

Cover

This is Part 4 of Rebuild Twitter with Laravel. Previously, you created the foundation, built profile and timeline. In this part, you’re going to introduce the tweeting feature to your user.

If you’ve done the previous parts, jump right to the planning.

If you’ve missed the previous parts, you can go back to Part 1 or Part 2 or Part 3. Otherwise, you can clone the project from Github. I’ll guide you how to install the project and continue to this part.

Offline version

If you are interested to study without the internet, you can get the FREE tutorials of this series in PDFs. Subscribe to my email list and I’ll deliver the PDF to your inbox.

iteachyouhowtocode.com

Setup the project from Github

Clone the project

Project link: https://github.com/co0lsky/rebuild-twitter-with-laravel Clone the project from Github

Configure application environment file

Duplicate the .env.example to be .env Configure database access. I recommend you to create a new database for this application. The table name has no unique prefix or suffix, it might clash with your existing table which is having the same name, like users.

Generate Application Key

Next, you should generate an application key. The application key helps to secure your application’s user sessions and other encrypted data.

Migration

Next, migrate your database.

Test

Launch your application.

Welcome page Register as a user.

Register page

Home page Alright, the application is ready.

Planning

Twitter allows you to include a link in your tweet, then, a link preview will be generated and present below your tweet. And, Twitter translate your link to a shorter link.

Twitter

In this case, you’ll build a link preview and an URL shortener modules that run behind the scene.

In the previous part, you built the timeline. You’ve crafted the Tweet table right. It is ready for the heavy job.

You allow your user to create a tweet. Like I mentioned before, creating a tweet is easy, it is an insert query. Behind this simple feature, you’ll add two features to make the tweet becomes more interactive and meaningful.

Alright, let’s summarise your planning, 1. Create a post box on Home page to tweet 2. Generate link preview for the URL user tweeted 3. Shorten the URL tweeted by user

Rebuild Twitter with Laravel was started before the Laravel 5.4 was released. This project is based on Laravel 5.3. It is been awhile and this project is going to left behind very soon (5.5 is coming soon).

So, let’s update to 5.4.

3 steps to upgrade to 5.4 from 5.3

It is easy to upgrade the project, it needs only 3 steps.

Step 1 – composer update.

Update your project’s dependency of laravel/framework from 5.3.* to 5.4.* and phpunit/phpunit to ~5.7 in composer.json.

Perform composer update.

Step 2 – Reinstall Laravel Tinker

Somehow, in the Laravel upgrade guide, it recommends reinstalling Laravel Tinker.

Add TinkerServiceProvider in config/app.php.

Step 3 – Clear cache

Once you’ve upgraded the project, the application may still cache the compiled services from the previous version.

Remove compiled services file bootstrap/cache/compiled.php

After that, flush the view cache.

Alright, these are the basic instructions to update from 5.3 to 5.4. If you want more in detail, check it out here.

Migration

Create a new table for storing the links from the tweets. Whenever user tweet with a link in the body, extract the link and insert into the Link table.

Alright, let’s craft the view.

Craft the view

Sample first is a very good framework on knowing what kind of information you need to pass to the view.

You build a sample link preview layout on the Home page.

Tweet with preview How does it look? The author’s user ID doesn’t fit there. Let’s display the author name instead.

Present author name

In the /timeline, author information doesn’t return in the response. You need to fetch the author information along with the timeline.

In Tweet, you create a new relationship between it and User. Tweet has an author.

To eager load nested relationships, you may use “dot” syntax. You eager load the timeline and tweet’s author information in one Eloquent statement

Display author’s name on Timeline.

Tweet with preview Alright, real work starts now.

Tweeting

Users share their stories to their followers via a simple text post, it is called tweeting. Besides the story, user tweet about interesting stories and inspiring articles from blogs or websites.

Let’s start with adding a post box on the Home page.

Add a post box

You add a post box like Twitter on top of the timeline.

Timeline

Create request

Then, create a custom FormRequest to hold the validation logic. In this case, tweet_body is expecting to post to the controller.

In the PostTweetRequest, there are authorize() and rules().

In authorize(), you can check whether the authenticated user has the authority to perform the request. However, you have the authentication logic in the middleware Auth to handle the part, so, simply return true.

In rules(), you declare the tweet_body as a mandatory field, only string, and accepts 140 characters or less only.

Controller

I believe you still remember the Single Action Controller (SAC) you’ve learned in Part 3.

You create a SAC which accepts PostTweetRequest and creates a new tweet in the database.

Routing

Don’t forget to add the new post URL into the route.

Post tweet If a user submits a tweet which is not fulfilling the requirements in the PostTweetRequest, Laravel will return error message before reaching to the PostTweet controller.

You are a good coder, you handle errors. You display the error message below the post box.

Error Next step, generate a link preview from the tweet that has a link within.

Link Preview

When user clips a link within the tweet, you don’t know what’s it about. A link preview gives the reader a quick glance at what’s behind the link.

In the planning, links are stored in a table and reuse for all the tweets. Although user will include one or more links in the tweet, there is only one preview only. So you bind the link to the tweet.

Add link_id as a foreign key in tweets table.

Perform the migration.

When a new tweet is created, call the fresh() to refresh the model with its newly generated ID.

Detect the link within the tweet body with a regular expression and create an entry in the links table. With the Link::firstOrCreate(), the model will create if the link doesn’t exist, otherwise, the existing model will return.

Now, generate the link preview.

Link preview generation

Link preview generation is an event happening after a new link created. You create a listener to listen to the link created event and perform necessary tasks.

Install the link preview package.

Register the event and listener.

Map the event with the link created event.

In LinkCreated, you inject the Link from the created event.

In NotifyLinkPreviewGenerator.php, you generate the link preview with the installed package.

Boom! The cover, title, and description are automatically filled up in the table after the link is inserted.

Post link

Database You display it on the Home page.

Link preview

Bug fix

You realise that the timeline is not sorting descending. The mutation of the created_at is the main cause, which is a bad call. Now you patch a hotfix to sort it right. In this case, you have updated_at which is not mutated yet.

Timeline The newest post is back to the top.

Okay, let’s move on to the next task, URL shortener.

URL shortener

With third party service provider, you can know what’s the trending stories your user are sharing, and the shorten link optimize the sharing across devices. Today, Bitly is your service provider.

Install the URL shortener package.

Register a new listener to listen to the LinkCreated event.

Before you can use Bitly’s service, you need an account.

Setup Bitly account

Register a Bitly account here if you have none. Then, generate a Generic Access Token at here.

bitly.com

Setup environment

Add BITLY_GENERIC_ACCESS_TOKEN to your application environment file.

NotifyUrlShortener

When a link created, shorten the link with the BitlyProvider with your Generic Access Token and update the short link to the database.

Upgrade view

In consideration of the same tweet layout will be used in another part of the application, like Profile page, you upgrade the div to become a Vue Component.

Home page

Home page Bang! The timeline look very nice now!

Conclusion

In real world development, your application will not work as expected all the time. There are many unexpected situations occur.

What if the link preview generation fails? What if the short URL connection timeout?

My advice, you can add a service constantly looking for the Link that is failed to generate link preview or missing short URL, and then broadcast an event. The convenience of the listener is it can listen to multiple events. The listeners you’ve created can pick up the job to patch the information.

Next Step

There are two things you can do

  1. Subscribe to my email list, I will email you when the next post is ready.
  2. If you find this guide helpful, share this guide to your friend. I feel grateful if you do that, I’m sure your friend will thank you as well.