Build A Link Sharing Website With Laravel

Building your own applications, even on a simple or small scale, is a great way to build your skills. This Link Sharing Website tutorial using Laravel will help us to do just that. If you’d like to save yourself a little time, you could just as easily head on over to http://www.easylaravelbook.com/ and pick up a great pre written application, PHPLeaks. PHPLeaks is a Link Sharing Website that has everything you need to get a nice starter project going. If you’d rather take the time to try and do all of this yourself for an exercise in learning, then read on!

I like to put things into a step by step sequence of events. This outline will provide us with each step to take, in order, when creating a basic website in Laravel.


#Choose a project name

We will go soup to nuts here, with everything built on top of Laravel Homestead. It’s the best way to have a reliable and flexible development platform right on your own machine. If you’d like to follow along, do install Laravel Homestead first. We’ll call our project angleslash, and we’ll want to be able to simpy visit http://angleslash.dev in our browser, and have everything work.


#Install Homestead

Getting Homestead running is a tutorial in itself. Just read the documentation to get up and running, or visit our article here at Vegibit that talks about configuring Homestead.

We’ll need to configure our Homestead.yaml file to add our new site to the homestead server. This is pretty easy, just make sure not to use any tab characters in the file, otherwise vagrant will bug out on you. Our current Homestead.yaml file has these entries in the sites section.

note: If you already have homestead running, you can still simply edit the Homestead.yaml, then run: vagrant provision, and you’ll be good to go. In addition, you’ll need to set your hosts file to add an entry for your new project. For windows this is located at C:\Windows\System32\drivers\etc\hosts Our current hosts file looks like this:

You can see that this homestead server has 3 different projects running all at one time. We have a base homestead.app project for various testing, we installed the larabook application from Jeffrey Way’s Laracast series, and now we have our new social link sharing website, angleslash.dev. Homestead really does provide a nice and convenient way to work on multiple projects at once. If you’re developing multiple websites, it is a must.


#Create the angleslash app

Now that we have everything ready to go, we can start building the project. The first thing we’ll need to do is ssh into our server.
vagrant ssh

Once we are logged in to our server, we can easily create a new project with Composer.
vagrant@homestead:~/Code composer create-project laravel/laravel angleslash --prefer-dist


#Set the Application Namespace

We can easily set the namespace for our application with Artisan, so let’s do so.
vagrant@homestead:~/Code/angleslash$ php artisan app:name angleslash

You should see the result, Application namespace set!


#Open the project in PHP Storm

Yes it’s a paid solution, but it’s the best. It also helps to really see how all of the code of a framework ties together. So if you don’t have it yet, go buy yourself a copy! We’ll add barryvdh’s ide helper since it is so fantastic to help us with code completion.

vagrant@homestead:~/Code/angleslash$ composer require barryvdh/laravel-ide-helper

Let’s add a few more packages that may be helpful while we are at it.

vagrant@homestead:~/Code/angleslash$ composer require guzzlehttp/guzzle
vagrant@homestead:~/Code/angleslash$ composer require illuminate/html
vagrant@homestead:~/Code/angleslash$ composer require laravel/cashier

Notice that since we simply used Composer to add the requirements, we don’t even have to manually edit or futz around with the composer.json file. All of that gets taken care of for us by composer which is nice.


#Configure The app.php file

Once the dependencies are set up the first place we’ll usually head to is the app.php file found in the config directory of the root namespace. In here we can configure some of the basic settings that any application will need.

First, we’ll configure our base url.

Next, we will populate the providers array with some new entries.

Finally we will configure the aliases array.

This will allow us to continue to use the original HTML and Form helpers from earlier versions of Laravel. For good measure, lets now do a composer update, then generate the docs for the ide helper. By completing the ide-helper:generate command, our code editor will now have intellisense like auto complete for Laravel. It’s a fantastic feature.

vagrant@homestead:~/Code/angleslash$ composer update
vagrant@homestead:~/Code/angleslash$ php artisan ide-helper:generate

We’ve done a fair amount of configuration, and we have a pretty nice base install of the Laravel framework going. Just to confirm, we’ll visit http://angleslash.dev/, and yes, we see the friendly splash page indicating that we have a successful installation of Laravel to work with.
Create Your Own Social Link Sharing Website With Laravel

In fact, the tutorial up until this point is a great workflow checklist no matter what type of project you might be creating. Jeez, I might need to bookmark this post!


#Configure Environment Settings

In the root namespace, we can open the .env file and set some information. Really the only thing we are worried about right now in this development environment is to set the database name. We’ll use angleslash as the database name for this project. All other options in the .env file will be left at defaults for now.


#Create The Database

Our application is going to need a database to work with. Since we have multiple projects going on our homestead server, we’ll need to create a new database to work with. Recall that the user for mysql in homestead is homestead and the password is secret. Lets create this database from the mysql terminal now.

vagrant@homestead:~$ mysql -u homestead -p
Enter password: secret

mysql> create database angleslash;
Query OK, 1 row affected (0.00 sec)

mysql> show databases;

5 rows in set (0.00 sec)

mysql>exit

Perfect! With that, we now have a database ready to use, and we can move on.


#Run Your First PHP Test

From the terminal, we can run the example test that comes with Laravel. This is the command to run it.

vagrant@homestead:~/Code/angleslash$ vendor/bin/phpunit

The test above simply ran the ExampleTest.php in the tests directory. Let’s take a look at the code involved.

It just makes sure that visiting the homepage gives back a 200 ok response.


#Create The Routes File

The routes file in Laravel gives us a high level overview of how our application will function. We can see all of the endpoints that need to respond to requests, as well as which controllers will be in use. Here is the routes file we have for our link sharing website. After we quickly review the routes file, we’ll then build out the link sharing website according to how we have our routes file configured.

Routes File


#Create Controllers With Artisan

We’ll next use Artisan to generate the controllers we’ll need in our application. I’m trying to become as familiar as possible with Artisan, since automatic code generation sounds like a great deal to me. First off, let’s just take a quick look at all of the code generation options available to us. We can do this by piping the output of php artisan to the grep command while searching for make.

vagrant@homestead:~/Code/angleslash$ php artisan | grep make

This is great! Artisan provides the ability to create new command classes, resources, events, middleware, migrations, service providers, and also the Form Requests which people have been raving about. Let’s quickly create all of the controllers we’ll need for our application.

vagrant@homestead:~/Code/angleslash$ php artisan make:controller UserController
Controller created successfully.
vagrant@homestead:~/Code/angleslash$ php artisan make:controller PostController
Controller created successfully.
vagrant@homestead:~/Code/angleslash$ php artisan make:controller SubController
Controller created successfully.
vagrant@homestead:~/Code/angleslash$ php artisan make:controller VoteController
Controller created successfully.

All of our controllers are now created. They are currently empty, but we are making progress with creating the skeleton of the application. Let us now create the Models.


#Create Models With Artisan

We are going to use the built in User Model that ships with Laravel, so we don’t need to create that. We will modify it slightly, and add some Eloquent Relationships to it a little later. We do need some models to handle our Posts, Post Votes, and Subs. Let’s create those now again using Artisan. Subs are just categories, like a subreddit.

vagrant@homestead:~/Code/angleslash$ php artisan make:model Post
Model created successfully.
Created Migration: 2015_06_01_175305_create_posts_table
vagrant@homestead:~/Code/angleslash$ php artisan make:model PostVote
Model created successfully.
Created Migration: 2015_06_01_175322_create_post_votes_table
vagrant@homestead:~/Code/angleslash$ php artisan make:model Sub
Model created successfully.
Created Migration: 2015_06_01_175337_create_subs_table

vagrant@homestead:~/Code/angleslash$ php artisan make:migration foreign_keys
Created Migration: 2015_06_01_181451_foreign_keys

Note: When we create each Model, Laravel automatically creates a migration for us. Since we have our migration files set up, let’s populate our migrations with the Schema we will need to support our basic link sharing website.


#Create Supporting Migrations

create_posts_table.php

create_postvotes_table.php

create_subs_table.php

create_foreign_keys.php

With our migration files now created, let’s run the migrations with Artisan to create the tables in the database we’ll need.

vagrant@homestead:~/Code/angleslash$ php artisan migrate
Migration table created successfully.
Migrated: 2014_10_12_000000_create_users_table
Migrated: 2014_10_12_100000_create_password_resets_table
Migrated: 2015_06_01_175305_create_posts_table
Migrated: 2015_06_01_175322_create_post_votes_table
Migrated: 2015_06_01_175337_create_subs_table
Migrated: 2015_06_01_181451_foreign_keys

If we log in to mysql and issue the show tables command on the database in question, we’ll see that our migrations did a great job of creating all the tables we’ll need.

mysql> show tables;


#Implement Our Models

We were able to use Artisan to create the boilerplate for our models. We still need to fill in the logic on our own. Just like filling in the code for Schema, this requires some thought by the developer. We will make use Laravel hasMany and Laravel belongsTo relationships. This is how we might do that.

User Model

Sub Model

Post Model

Post Vote Model


#Implement Our Controllers

Just like our Models, we need to still fill in the logic of our controllers. We have to account for the User, Sub, Post, and Vote Controllers. Let’s do that here.

User Contoller

Sub Contoller

Post Controller

Vote Controller


#Create Form Requests

We’re making some serious progress here. In the above section when creating our controllers, you may have noticed that we used type hinting in the store methods for both the Sub and Post controllers. This is a really slick way to complete validation with the awesome new feature in Laravel, Form Requests. The way it works is, we can simply create a new Request using Artisan, and then fill in the validation rules for the request. Once this is done, we can simply pass in the request to the associated method where we need to validate data. Let’s create our Form Request for both the Sub and Post now.

vagrant@homestead:~/Code/angleslash$ php artisan make:request SubFormRequest
Request created successfully.
vagrant@homestead:~/Code/angleslash$ php artisan make:request PostFormRequest
Request created successfully.

SubFormRequest

PostFormRequest

All we had to do was provide the rules for our validation. Form Requests are a really fantastic new feature of Laravel.


#Create Associated Forms

We need to create two new forms for our application. One for creating a new Sub, or category, and another for creating a new Post or Link. Since we are using Laravel’s built in forms for Registering and Logging in, we don’t even need to worry about those. If you want to dig into creating forms, you can also check out this laravel forms tutorial. Here is the code for both of our forms.

createsub.blade.php

submit.blade.php

Note: We did add a small bit of logic to include the ability to add an error class to whatever form field fails to validate. For example, if you enter an invalid URL and submit the form, when it comes back to the form with errors, not only will the application spell out the problem for you, but the URL form field will have a red outline around it via the Bootstrap has-error class.


#Create A Master Layout

Blade is growing on me in a major way. The more you use it, the more you love it. In this master layout for our link sharing website application, we’ll include all of the asset resources we need to support us. Here is our master layout file.

default.blade.php


#Create Sub, Post, and Profile Blade Views

sub.blade.php

post.blade.php

profile.blade.php

snippets/post.blade.php


#Implement a Helper Class

You may have noticed in our view file we referenced a method like so Helper::timeAgo(). In order to make that available to us in our views, we’ll need to include this class in our application. This is how we did it here. In the app folder, where the models live, simply add a file named Helper.php. Place this code inside of it.

Helper.php

Modify the autoload block in composer.json to include this file.

Finally, run composer dump.

vagrant@homestead:~/Code/angleslash$ composer dump
Generating autoload files

The helper is now available to us in our views.


#Implement Post Votes With Ajax

We need a bit of JavaScript to provide for the ability to vote on Posts via ajax. Here is the code we use to accomplish this.

main.js


#Set redirectTo for Laravel Auth System

Laravel’s built in registration, login, and password reset features are really fantastic. By default, these features redirect you to /home which might be the dashboard of your application. In our case, we simply use / as the “home” of our application. To set this, simply open both the AuthController.php and PasswordController.php and add this one line.


#Screenshots of Angleslash

We’ve done a lot of work up until this point. We are now ready to take our link sharing website application for a spin. We’ll make use of a handful of excellent links to test our link sharing website application. Let’s try http://laravel.com, https://leanpub.com/easyecommerce, https://laravel-news.com/, and http://www.easylaravelbook.com/ Let’s check it out!

Registering A New User

Registering A New User

Creating a New Sub

Creating A New Sub

Submitting A New Link

Submit A New Link

Viewing A User Profile

Viewing A Profile

Cool Modal Effect for Logged Out Users

If a guest or non logged in user tries to click the vote buttons, either up or down, they will trigger a modal that will request them to either register for a new account, or log in with their existing account.
Modal Trigger For Non Logged In Users

Viewing The Front Page of Angleslash

Laravel link sharing website

Build A Link Sharing Website With Laravel Conclusion

This has been a really fun tutorial that put the rubber to the road on a sample Laravel application. The goal was to cover an example Laravel workflow in a soup to nuts fashion, starting with Homestead, and covering a wide range of topics including choosing a project name, creating a new application with Composer, setting a namespace with Artisan, using PHP Storm for code editing, configuring a base url, configuring environment settings, running a sample PHP Unit test, creating a routes file, using Artisan to generate Controllers, Models, Migrations, and Form Requests, as well as completing very basic styling with Bootstrap.