How To Seed A Database In Laravel 4

I have been writing a lot about Laravel lately and recently I was asked about database table seeding. Chances are you already use the awesome migrations feature, but probably don’t use database seeding. I have seen people using migrations to seed a table, but it’s messy and not exactly ideal. Using the seeding functionality in Laravel, you’ll discover how easy it actually is.

When should I use seeding?

I personally use seeding in Laravel quite extensively during the development phase of a web application. Being able to add in mock user accounts, pages and other data for testing purposes is a lot easier than manually doing it every time.

Another use that I find myself using is seeding roles and permissions. In my web applications, I will generally have a basic set of permissions that every Laravel site will get (admin, guest and basic user roles) as well as some basic permissions.

A precursor

Where to put your seed files?

All custom seeding classes go into app/database/seeds a new installation of Laravel 4 will have a file called DatabaseSeeder which is where we will call our custom created seed class(es) to fill our database with content.

What do I name them?

The name of your custom seeding class does not matter. However, it is advisable to name your seeding classes in camelCase. If you are wanting to seed a roles table in your application, you would call it something like RolesTableSeeder or SeedRolesTable

In action

Now we’ve explained the basics, when to use seeding and how it can help us, lets get to the meat of the post.

Rather than explain step-by-step, I’ll show an example of using seeding instead.

The custom role seeding file app/database/seeds/RoleTableSeeder.php


<?php

class RoleTableSeeder extends Seeder {

    public function run()
    {
        // Delete any content in the roles table
        DB::table('roles')->delete();

        $role_data = array(
        	array('role_name' => "Administrator", 'role_description' => "Administrators can do everything on the site"),
        	array('role_name' => "Moderator", 'role_description' => "Can edit, approve or reject content"),
        	array('role_name' => "Basic", 'role_description' => "Just a basic user")
        );
        
        foreach ($role_data AS $role) {
            Role::create($role);
        }
    }

}

Calling our newly created seeding file

In the file app/database/seeds/DatabaseSeeder.php you will notice a run function. Within this function beneath the Eloquent::unguard function call, we will call our seeding file.


<?php

class DatabaseSeeder extends Seeder {

	/**
	 * Run the database seeds.
	 *
	 * @return void
	 */
	public function run()
	{
		Eloquent::unguard();

		$this->call('RoleTableSeeder');
        $this->command->info('The roles table has been seeded');
	}

}

Front-end Component Driven Development

As the web continues to evolve and front-end development continues to become even more complicated, the need to adapt and implement processes for workflow grows immensley.

Photoshop is dead

We are well and truly living in the golden age of front-end web development. Photoshop is dying, designers and developers now design on the fly using HTML and CSS. This isn’t to say Photoshop is going away completely overnight, but the transition is well and truly in motion.

As more and more people come across to the code side, processes help ensure there is order amongst the chaos. This is where component driven development can kill two birds with one stone.

BEM

I haven’t made it much of a secret that I love BEM. I was late to the game to be honest and the version of BEM that I personally use is a modified variant of the original which isn’t all too different.

My BEM Variant

.blockName
.blockName--modifier
.blockName-childElement

In conventional BEM, an element that is a child of a block is usually dictated by two underscores. It’s just personal preference, but I can’t stand the sight of double underscores, they look ugly. So I opt for a single hyphen instead and use camelCase for the naming of a modifier, child element and of course, block name.

I believe this particular variant is easier to type, everything follows a more natural order in my opinion.

Component Based Living Styleguides

The next step in a component driven workflow is to use some kind of styleguide, preferably a living styleguide. The general idea here is to develop each individual element in your web application using HTML/JS and CSS. Break up each section of your web application into logical components, below is an example:

<nav class="navigation">
    <ul class="navigation-list">
        <li class="navigation-item">Home</li>
        <li class="navigation-item">Categories</li>
    </ul>
</nav>

<form action="/search" class="search" method="POST" role="form">
    <input type="text" name="search" class="search-field" placeholder="Search the site...">
    <input type="submit" class="search-button" value="Search">
</form>

<div class="media">
    <img class="media-image" src="yourimage.jpg" alt="Some Image">
</div>

It is worth noting that not everything should be broken up into a component. A heading for example can be a part of a component and outside of a component, so not everything should be BEM’d. However, it is possible that a heading two within a section block will be smaller than a heading two outside of a component.

The Benefits of A Living Styleguide

The benefits of a living styleguide are you can make changes on the fly and they will accurately reflect real life immediately. Photoshop is good at making things look good, but in most cases, what you see in Photoshop isn’t what you’ll see in a web browser (especially comparing between Windows and Mac).

Another benefit of a component based living styleguide is the self-documenting nature of a styleguide. If you can see and possibly interact with a component, it will speak volumes for how it works. It also allows developer and non-developer team members to add in a feature to a page without needing to know a single line of code.

Encapsulating functionality and style into a component also means if you make a change, it will be restricted to that component only and won’t affect anything else in the page. Using modifiers, you can change the component depending on the context.

How To Remove Border-radius Rounded Corners From Buttons In Bootstrap 3

In Bootstrap 3, the buttons (well a lot of elements) have a border radius value giving them rounded corners. Now I don’t know about you, but I find rounded corners on buttons horrible.

If you are using the LESS version of Bootstrap, set the following variables:

@border-radius-base: 0px;
@border-radius-small: 0px;
@border-radius-large: 0px;

If you are using Bootstrap SASS port, set the following variables:

$border-radius-base: 0px;
$border-radius-small: 0px;
$border-radius-large: 0px;

Does Using HTML5 Markup Tags On Your Website Improve SEO?

I was asked this question by a colleague recently when discussing SEO and modern front-end web development. I think most of us assume that using proper sectioning elements that HTML5 provides us would help with SEO a tiny bit, so I set out to find the answer and you might be surprised.

Understanding semantics

In HTML5 we have tags that provide semantic meaning like; main, section, aside, figure, article, header, menu and footer (amongst many others). Using these tags in our page makes for better structure, it also means when Google comes along they don’t have to guess what content is what in your page.

But, there is a flaw. Like the good old days of being able to stuff keywords into a page and make them hidden, HTML5 semantic tags can be abused. What is stopping someone from saying a particular section is an article when it’s nothing at all? There is confusion around when to use what tag, do I use section or article, do I nest one inside of another?

What Google wants

When Google visits your site what are they most interested in: the page structure or the content? While I am sure Google does care to an extent how you mark up your pages, they’re not going to reward or penalise you for trying to properly structure your content. When Google visits your site, they’re analysing the content, they’re analysing other metrics like in-bound links, outbound links, keyword density, topic ratio and more.

Analysing top websites

The true test of whether or not HTML5 structure actually gives you an edge is to search for more popular terms and compare the markup of pages.

Some popular terms that I tried out include; music, news, concerts and movies. The results are not all too surprising.

Search term “music”

The total number of sites in the top 6 of Google search results for the term, “music” using HTML5 semantic elements was one. The site using HTML5 sectioning elements in my results set was result #6 Allmusic.com which was using some sectioning elements and possibly other elements elsewhere.

Screen Shot 2014-08-28 at 4.27.32 pm

Search term “news”

The total number of sites in the top 6 of Google search results for the term, “news” using HTML5 semantic elements was zero. Not one single site used a HTML5 tag on the landing pages linked from the search results page.

Screen Shot 2014-08-28 at 4.33.35 pm

Conclusion

So, what does this conclude or prove? Pretty much nothing. It does however show that having or not having HTML5 tags doesn’t give you any advantage or disadvantage, at least for the moment. This wasn’t an in-depth investigation, but I can say with almost certainty Google does not care if your site is built using DIV’s or article and section tags, it cares about your content and the credibility of it for the most part.

How To Prevent Duplicate Form Submissions Using jQuery

If you’re using jQuery to AJAX post a form then you’re already more than familiar with the caveats of using jQuery to POST a forms contents. One thing I often see overlooked is the disabling of the form while the content is being submitted, there is nothing worse than receiving duplicate form submissions and knowing the fix was simple. Or worse yet, I’ve seen instances where a form has been used to attack a site by constantly submitting it quickly.

Disable EVERYTHING

This is an easy solution to implement and in my opinion, the best compared to other methods I have seen. When the form is submitted provided it passes validation (you do validate your forms client-side, right?) you simply disable the submit button by setting its disabled attribute to true like so: $(“#yourbutton”).prop(“disabled”, true) – now for as long as that button is disabled, it won’t trigger a submit event on your form.

I then go one step further and remove the “action” attribute from the form, storing its value in a variable first, in-case I need to add it back. That way if someone enables the button via the browser Web Inspector, the action attribute is gone and therefore the form can’t be submitted. If the request fails, you can add the “action” attribute back to the form (if needed).

An example


$("#get-quotes-form").submit(function(event) {

	// Put form validation here for checking fields

	$("#get-quotes-button").text("Sending...").prop('disabled', true);

	var $form 		= $(this),
		data 		= $form.serialize(),
		url 		= $form.attr('action'),
		postRequest = $.post(url, data);

	// No matter what, remove the form attribute
	postRequest.always(function() {
		$form.removeAttr("action");
	});

	postRequest.done(function() {
		// Request is successful
	});

	// The request has failed, return the form action attribute
	postRequest.fail(function() {
		$form.attr("action", url);
	});

	event.preventDefault();
});

How To Fix A Site Affected By The Google Panda/Penguin/Phantom Updates

Recently I encountered one of Google’s latest search engine algorithm tweaks and saw a site that was getting roughly 500 visitors a day drop down to less than 70 visitors per day. It was shocking to say the least, but kind of expected.

I left the site, updated it occasionally and noticed the traffic remained low. This wasn’t a problem that was going to solve itself, I knew I had to try and fix it and return the site to its former glory.

Understanding the penalty

Unless you were unfortunately an innocent victim of one of Google’s cute but deadly sounding updates, there are a multitude of reasons.

The site I operate is kind of grey area and relies on capturing type in traffic for popular things like movies, games and music. I am not linking to anything, but through some clever SEO and named pages, I was once ranking quite well for popular music and movies.

I determined the reason my site was penalised is because most of the page content was mostly copied from the likes of Wikipedia and wasn’t really unique. I was copying the content word-for-word and for a good amount of time, it worked without an issue. I tried spinning the content to mild success as well.

Fixing the penalty

The latest slew of Google algorithm changes look at the content of your site and determine if you add any kind of value, obviously copying and pasting Wikipedia content wasn’t adding value at all. To fix the issue I had to think of ways to spin the content to add value without making more work for myself.

Previously a page for a popular movies might have had the title: “Movie: How To Train Your Dragon 2″ and then on the page I would had the following content:

  • The title
  • The copied content from IMDB or Wikipedia
  • A Youtube embed
  • A poster image
  • Occasionally release dates

The new page layout for a movie now has the following:

  • The title
  • Release Year (Clickable taking you to an archive page of movies released the same year)
  • Release Month (Clickable taking you to an archive page of movies released the same month)
  • Budget
  • List of actors and actresses
  • List of directors
  • The ability to click on an actor, actress or director to view an archive page showing other movies they’ve starred in or directed
  • The movie category (clickable taking you to an archive page showing other movies in this category)
  • Multiple Youtube embeds (official trailer, preview clips)
  • A news section with links to news articles about the movie including excerpts
  • A widget that polls a few torrent sites determining if this movie has leaked onto the Internet (with manual override) and also support for users to subscribe to leaks of this movie
  • Ability to download movie trailers (using a custom API script I developed to save Youtube videos)
  • Page specific discussion (a custom forum category)

Has it worked?

At first I wasn’t so sure, but then recently I’ve noticed my traffic has started growing. It took about a week before Google visited my site again and obviously re-assessed whether it offers value or not. I’ve gone from around 60 hits per day back to 200 in a little over a week and a half. So I guess you could say it worked and provided I don’t get penalised again and keep the content coming, the traffic should be back where it was soon enough.

The key here is you have to make your content look unique even if in reality your site still doesn’t really offer that much value. As long as you can deceive Google enough to look fresh, then that is all you need.

Solving "sh: mysql: command not found" In MAMP Pro 2 and MAMP Pro 3

If you are reading this there is a possibility you have run into this error message in your terminal window: sh: mysql: command not found

This error is being displayed because MAMP Pro stores MySQL in a location on your Mac that isn’t added to your main $PATH. MySQL is stored in the MAMP Pro bin folder here: /Applications/MAMP/Library/bin/mysql

Fortunately the fix is rather simple following the below steps:

  • In your home directory create or edit the file “.bash_profile” you can access your home directory by typing: cd ~/
  • Add this to the top of the file: export PATH=$PATH:/Applications/MAMP/Library/bin
  • Save the file and then restart your Terminal
  • In your newly restarted Terminal window type: mysql –version

This will now map MySQL to your path and allow you to access it by just typing “mysql”

Adding Location Based Search To Your Website/Application Using Google Places Autosuggest

If you have used Airbnb before, then you would be familiar with the location field where you type your desired location and it gives you a dropdown of suggested places based on what you type.

I have seen sites that try and build their own location databases, but we all know it can be a difficult and sometimes expensive task to obtain up-to-date global location information for cities, landmarks, postal codes, regions and more. The Place Autocomplete API gives you the power of the Google Maps search dropdown without needing to buy the data.

The field isn’t only just limited to getting global addresses and locations, it also allows you to enforce restrictions on countries, cities and localised areas. You can also obtain every single component of the address selected from the field as well. You can specify a search radius, display results based on the users current location and more.

Surprisingly, there are a lot of developers out there rolling their own locations functionality into their web applications, when Google gives you a powerful API and comprehensive database for free. So stop building your own solutions and use the Place Autosuggest API here.

The Expendables 3 Movie Piracy Conspiracy Plot

Recently Variety posted an article titled Expendables 3 Flops: Is Piracy To Blame? in which a case is made whether or not the movie leaking onto torrent sites 3 weeks before its official release damaged it at the box office.

The movie fell short $10 million of its expected $26 million, debuting at $16.2 million in revenue which is atrocious when you compare that to other movies that debuted at the same time as it did like Teenage Mutant Ninja Turtles and Lets Be Cops.

Deliberate

I am stating the case that this was a deliberate leak from the studio themselves. A movie leaking its own movie weeks out from its release? Crazy, right? Well, not if you think about it logically.

Movie piracy is at an all time high and studios don’t know what to do. They’ve tried lobbying for three strikes policies, ISP level filtering and taking down the torrent sites themselves to no avail for years now.

The issue is while studios will have you believe that the industry is shrinking and dying, the good movies are still making great profits.

Here are some movies released in the last couple of years that have ranked amongst the most profitable movies of all time.

Rank #13 – Transformers: Age of Extinction (2014) at $1,054,437,000
Rank #5 – Frozen (2013) at $1,274,219,009
Rank #6 – Iron Man 3 (2013) at $1,215,439,994
Rank #22 – Despicable Me 2 at $970,761,885

It might surprise you to know that not one single movie in the Expendables series has ranked even last on the highest grossing movies. The maximum amount this series has made is $34.8 million for the first movie, which while not completely horrible, still wasn’t that great.

Does that tell you something? It tells you this franchise is dead in the water and people have stopped caring. The fact the third movie was made for PG 13 audiences and up when the two previous films were R rated tells you something else as well. Young teens would prefer to see Guardians Of The Galaxy over a film comprised of dads favourite action stars from the 80′s and 90′s.

Is piracy sort of to blame?

You can’t rule out the fact a movie leaking almost a month before its debut and being downloaded by 2.2 million people would not have at least some effect, but I think the effect the leak had is being greatly exaggerated.

In 2009 the film X-Men Origins: Wolverine leaked before its release (albeit a unfinished cut, but still the full movie) and it went on to gross over $373 million at the Box Office, the movie had a budget of $150 million. Even though this particular X-Men movie received pretty bad reviews, it still went on to make a lot of money.

The Scapegoat

Why would a studio leak its own movie that they sort of probably knew was going to flop? They needed a scapegoat. The leak and discussion around lost revenue comes at a time when the entertainment industry is at a stalemate. They’ve tried lobbying for three strikes policies, they’ve tried getting the ISP’s to shoulder the blame and police users and they’ve tried suing infringers to no avail.

You can’t deny the paltry figure The Expendables 3 made at the Box Office looks pretty bad on paper, especially when your movie leaked almost one month prior, it makes for a pretty strong case that piracy was the reason when the sane of us know it wasn’t the contributing factor.

What better way to get people on your side and to try and turn the tide in the copyright/piracy debate than to present some harsh numbers that work in your favour?

You could call it a false flag attack on the entertainment industry. However, it’s just a theory and logical arguments like why would a studio fund a movie that they knew would flop and cost them lots of money and damage their reputation?

My Soundwave Festival 2015 Wishlist

The now massive and widely successful Australian music festival for rock, punk and metal genres is back in 2015 with a new two day festival format. This is due to complaints from prior years with timetable conflicts, disagreements with larger bands wanting headline spots and overrall the standard festival issues that arise.

Personally I am really excited about the rumoured bands for the festival. My ideal line-up would contain most of, some or best case scenario all of the following bands. Following the traditional Soundwave formular we can expect to see a lot of bands that made an appearance and didn’t piss AJ Maddah off making an appearance at Soundwave Festival 2015. Some of the bands on my wishlist played Soundwave Festival 2012, so there is a good chance some of these bands will be there.

Thrice

This is a 1000:1 shot since the guys are currently on a hiatus, but if AJ could pull some strings to get the guys to play one last Australian show (the band never made it out here for a farewell tour) my dreams would be realised. We sadly didn’t get to hear Major/Minor material live, bring the band back for one last Soundwave performance. I would pay double the ticket price to see Thrice added to the lineup, I would cream my pants if they were not only added, but also headlined.

He Is Legend

I think He Is Legend would be a perfect fit for Soundwave. They’ve just released a new album, they haven’t toured Australia in a very long time and they are absolutely brilliant live.

Slipknot

There is a strong rumour that Slipknot is going to be one of the headlining bands of Soundwave Festival 2015. In-fact, AJ has openly stated the band can play any time they want, every year if they wanted too. The guys are gearing up for a new album release and the timing would fit in with Soundwave really well. The $180 cost of a ticket for two days of Soundwave would be worth seeing Slipknot alone.

The guys played Soundwave 2012, further propelling the rumour even further that this is a possibility.

Parkway Drive

Even though Parkway Drive can headline their own tours, now that Big Day Out is gone, Soundwave is the premier festival for these types of acts. AJ has openly stated they are always welcome to play, so if they agree, they would be an excellent addition.

Volumes

These guys are absolutely blowing up right now. Progressive metallers Volumes just released a new album and have been doing the rounds of some US/UK festivals. From what I have seen, they put on a great live show.

Every Time I Die

Supposedly it is all but confirmed these guys will be making their Soundwave Festival debut in 2015. ETID coupled with the addition of He Is Legend would make me froth at the mouth in excitement. The band toured for Soundwave Touring last year, so this all but confirms they’ll be making an appearance.

Deftones

The last time the band played Soundwave was its debut in 2007. What a great year, getting to see Thrice and Deftones perform was an amazing treat (right after one another). Since then obviously losing Chi was a big deal for the guys, they are planning on releasing a new album in 2015 and would be a great addition to headline again.

Rise Against

There is a VERY strong possibility the guys will be playing Soundwave 2015. Apparently they’ve openly stated they’ll be here in February/March 2015 to tour, all but confirming we get to see them either way. These guys are a class act and always a treat to see live. And surprisingly, this would mark the bands first Soundwave appearance.

Job For A Cowboy

A band of great guys making great music. Always put on a great live show and apparently all but confirmed to play Soundwave 2015. Hopefully this is the case.

Falling In Reverse

Even though front-man Ronnie can be a douche, you can’t deny FIR are a great band. If anything, I would see these guys (permitting there are no conflicts) just to see Jackie Vincent shred it up in person. The only possible thing stopping this happening is if Ronnie runs into Visa issues like he has in the past trying to enter Australia. If they’ll let Snoop Dogg in, surely they’ll let Ronnie in.

The Plot In You

I really enjoy the music these guys out. They’ve never played the festival and are currently gearing up to release a new album late 2014/early 2015. The timing would line-up perfectly with the schedule fo the festival.

Like Moths to Flames

Another potential band for Soundwave I would love to see added to the line-up. They released an album in July 2013, I am a fan of this bands music and think they would put on a great live show.