Smiley Happy Coder

Fixing the PDO Exception in your first laravel migration under MAMP

I admit, this one has caught me a couple of times so I thought I’d write a very quick post about it.

Each time I install Laravel on MAMP I get a PDO Exception issue and I wonder why.

PDO Exception

The issue arrises when MySQL tries to connect. MAMP prefers connecting via a socket so the easy fix is to add this line to database.php

'unix_socket'   => '/Applications/MAMP/tmp/mysql/mysql.sock',

That’s all folks, worlds shortest blog post.

  • Top

Making bash scripts run globally

To make your scripts run globally you need to place them in a specific folder.

Bash scripts run globally

When you enter a command at the prompt the system will head off to this bin folder to check if a programme exists there first. If it doesn’t then you get an error message. My bin folder is /usr/local/bin/

To make scripts run globally, move the script to the correct folder

NOTE: Please don’t actually do this step. You’ll see in a few minutes.
To make the scripts run globally you can simply move them to the bin folder. This command ought to do the trick

mv /usr/local/bin/

Now you can just type anywhere and the script will be found and run.

But, we can do better

While this works well, it now means if I want to do any work to that file I need to move to the bin folder to do it. Personally I have the file in git version control in my Dropbox. I could just re-copy the file after each update but thats just a pain.

Lets not actually move the file, but make the system think its there. How can we do that?

Symbolic Links

A symlink is like an alias. Its just a link that says this here points to that over there.

And now you see why I said not to do the previous step

So I ran a command to create my symlink

ln -s ~/Dropbox/scriptname/ scriptname

And now I can just type scriptname anywhere on my system and boom it works.

The astute amongst you will have spotted that the file extension. Since unix doesn’t really use extensions I was able to set the symlink to omit the .sh extension.

Beware of existing program names

Placing the script in the bin folder is great but you have to be careful not to name your script the same as an existing unix program.

  • Top

Get the first element in an array using PHP reset

PHP Reset
In my last post we discovered how to find the last element in an array by using the end() function. This is brilliant and no doubt going to help you out on a regular basis. But now we’ve set the pointer to the end of the array, how do we get it back to the start?

We use the reset function of course!

The reset function can be used like this
$things = [ 'bat' , 'sponge' , 'cabbage' ];
//Lets just jump to the end of the array for the fun of it.
end( $things );
echo reset( $things); //Will echo "bat"

Now you might be thinking, “Why the heck do I need to remember this function, when I can just call the 0 index?”

I have to admit I totally agree, surely something like this is exactly the same thing?
echo $things[0];

Anyone any thoughts as to why reset is better if, in fact, it is?


Thanks to @olimortimer for highlighting a couple of bugs, now been fixed.

@WarpcodeUk also suggested that this would be a viable answer to handle associative arrays. Using reset() in this case would simply return the first array.

$things_values = array_values($things); echo $things_values[0];

Thanks very much to both.

  • Top

Select the last element in an array using PHP’s end function

PHP end function

Arrays play a huge role in most programming languages. I use arrays in PHP many times every day.

Finding the last element of an array can be a useful thing to know. So how would you go about it?
Well the junior developer might think that this is a good answer.

$things = [ 'car' , 'toaster' , 'tree' ];
$count = count( $things ) - 1;
echo $things[ $count ];

So what is the thought process here?

I know I can get an element by passing the index. Like this echo $things[2];
Firstly I need to know how many elements are in the array so I’ll use count() to tell me that.
But, damn, arrays are zero indexed so count() in this instance will return 3. Okay so just take one off.
Thats it, its working.

Some programming languages offer things like

But not PHP, that would result in an undefined index. :-(

While this way works there is another, better way. Introducing the end() function!

$things = [ 'car' , 'toaster' , 'tree' ];
$count = count( $things ) - 1;
echo end( $things );

The end function literally just moved the current position within the array to, you guessed it, the end.

The function returns the last element of the array or false if the array is empty.

This is really useful because now I can just echo out the content of that element.

The end function also works on multi dimensional arrays just as well as flat arrays.

  • Top

Using customers secure account passwords in a sensible way

Secure Passwords

Being a web developer it is sometime necessary to log in to some of our customers accounts and therefore know their passwords. Accounts like domain registrars or social media services. Some of our customers don’t give a seconds thought to their passwords security and happily hand them out to any Tom, Dick or Harry, or even me!
Now I suppose I could be flattered that they have this level of trust in me and I have never and would never abuse that trust, but some people might.
I sometimes come across users who are completely on the other side of the spectrum and won’t hand out passwords at all. I completely understand but that can occasionally make my job difficult to do.

Trusting me with passwords

Trust is an interesting thing. Just like their passwords some folks throw it around like its nothing and others really make you earn it. I personally feel it should be earned to some level. But this isn’t about me.

Sometimes its not even as much about trust as it is about the fact that this password is the same as they use for their bank accounts or mobile phone provider. Now the astute amongst us know that this is a bad idea to use a single password but people still do it.

Storing Passwords

I would rather not store peoples passwords. Where should I keep them? Is what I would call secure the same as the owner? Do I keep them on a Post It stuck to my screen? What happens if my machine is lost or stolen?

I use a product called 1Password to store my passwords but that isn’t a decision I can make with customers passwords.

So whats the answer?

Well I’m not going to say that my method is the only answer but it is certainly an answer.

Each time I need to access a customers account I always suggest that it might be a good idea for them to reset the password to a new password which they don’t mind sharing with me.
I can then go off and do what I need to do and then they can change the password back.

This way I have the access I need to do my job but only for as long as I need it. The customer also has piece of mind that their account stays within their control.

  • Top

A good specification in plain English

Let me take you back to America in the early 60’s. One of the most important men in the world at the time, JFK, petitioned the US Congress to put aside adequate funds in order to, in his words “Land a man on the moon and return him safely to the Earth.”
You could say that this was a specification. NASA was challenged to take a man from the Earth, to the Moon and back. This is pretty much a user story.


User Stories

Most projects, be it interstellar travel or building a new website, involve a lot of different people with all sorts of technical ability. So why do we insist on writing these massively complex specification documents that are confusing for everyone except the developer who wrote it. This is where User Stories come in.

What is a User Story?

A user story is a way of writing a specification in a non technical, but none less accurate or in depth way. The American public, effectively the customer if were sticking with the Moon landings as an example, hasn’t the first clue about building larger rocket boosters or the challenge of coupling two spacecraft moving at thousands of miles an hour in orbit of the Moon. Why should they? The understand that men will be transported to the Moon and back again.

Lets switch back to web development, I know a bit more about that than travel in outer space!
Lets say a customer engages you to build a new e-commerce website for their business. Does the customer need to understand the intricacies of creating an order object? Or just that items can be added to the basket? Do they need to know about recalculating basket quantities including rebuilding coupon code calculations? Or just that the user is able to update basket quantities?

I think you can see where I’m going.

Using User Stories we can draft a good quality specification that has just enough pertinent information to make it useful but not so complex as to baffle the customer.


The danger with User Stories is becoming too generalised within the story. Lets take JFK’s user story. “Put a man on the Moon”.

After a matter of weeks the Director of NASA contacts the White House to report that they are ready to perform their task, to “put a man on the moon”.
The President, half of the White House and various Generals from all branches of the US Military all travel to the launch site in anticipation of the making of history.
When the president questions the director of NASA on how they were able to come up with a viable plan so fast, the director replies, the specification was so simple.

The gathered throng of dignitaries all make their way out to a specially erected seating area, spirits are high and silence soon falls. The assembled crowd are all staring up at the huge wooden structure before them. Not wishing to question to intellectual prowess of the scientists and engineers at NASA, no-one utters a word. In the distance a man wearing a flight suit steps up towards the capsule. He forlornly looks up and waves at the visiting guests who applaud this brave, soon to be, national hero.

After what seems like an eternity the astronaut is secured into his capsule. The engineers and scientist all move back away from the structure in readiness for launch. The clock is started. As the seconds display zero there is a massive noise, not a noise that the visitors were expecting. More of a wooden noise, sounds of wood splitting under huge stresses. After what seems like an age the capsule leaves the launch pad. It rises at a frightening rate and soon disappears from view.

Once things calm down the President pushed his way through the crowd to the director of NASA. “You built a giant catapult?!” The director is shocked. At that moment the silence was broken by a voice coming over the tannoy “The capsule has impacted the surface of the moon.” The scientists and engineers all look very happy with themselves, whoops and high fives are exchanged.
The President, remaining silent throughout the launch does not look pleased. Red faced he shouts “Impacted? What do you mean impacted?”
The director looking startled replies “We’ve done exactly as you asked, we put a man on the moon”
“How do you propose that we get him back?” asks the president. The director quickly the folder tucked under his arm, he seems to read something to himself and then looks up. “You didn’t ask us to return him, you asked us to put a man on the Moon, which we have”
“But, he’ll die” sobs The President the realisation setting in.
“Oh, no need to worry about that, he suffocated long before he left the atmosphere.” replies the director. The President was a gasp.


Sorry if I disappeared into a bit of a work of fiction for a while but I think it illustrated my point.
The User Story in this case was “To put a man on the Moon” when in reality it should have been as The President originally asked.

Now I’d imagine that NASA had a much more detailed and well thought specification that was probably even signed off by the customer, but thats another post.

I hope my ramblings made some sense, while User Stories can be very useful, serving to simplify the specification process, care needs to be take to not over simplify.

  • Top

PHP Storms Live Templates

I have been using PHP Storm for a long time now. I love it, its such an amazing IDE that I still just scratch the surface of.

One thing I use a lot is Live Templates.
PHP Storm Live Templates

What are Live Templates?

Live Templates are what you might think of as snippets, small chunks of code (or maybe just text) that you use and re-use all the time.
In my mind, a dark and scary place, the reason that Live Templates aren’t called snippets is because they go way above and beyond what you’d think of as a snippet.

Just snippets

Yes, you could just use Live Templates as a snippet library and that would be fine. You’d save a bunch of time and everyone would be happy. I certainly use simple templates.  Like a lot of developers I use Bootstrap a fair old bit. One thing I write, like I’m sure you do, is the syntax for a row.
Just like this
<div class="row">

Now you might be thinking that this chunk is only twenty odd characters and you’d be right. So why bother. Well in my case I just type
And then hit tab.

Live Templates can be initialised by a few different keys, I leave mine as the tab key.

Now the astute amongst you will immediately spot that this is only four characters. Well thats better for me, its faster and easier.

Lets get a bit cleverer

We’ve seen pretty much the simplest implementation of a Live Template, and while its cool, we can do better. Much, much better.

Live Templates have the ability to insert your cursor for you just using a variable that you can enter.
This means that the above snippet actually looks like this.

<div class="row">

This now means that my cursor is just sitting there in the right place, the obligatory four spaces indented, ready for me to just keep going.

Cleverer still, you say?

Okay so we’ve added a nugget that helps, but sticking with the Bootstrap theme lets get a bit cleverer.

I often use columns in Bootstrap and they’re a fair chunk of code. Something like this.

<div class="col-sm-12 col-md-6 col-lg-4">

In order to create a column I need to specify how wide this column will be at each break point.
So in this case the mobile view, it will be the full width, on tablets it’ll be half the width and on a desktop screen it’ll be a third of the width.
Now in reality we could just create a snippet for each possible permutation of these columns but as I’m sure you’ll agree there could potentially be hundreds.

Live Templates to the rescue!

We can create a snippet that’ll really simplify this process by using variables. Similar to the $END$ variable we saw above but with the ability to type into the variable.
Now my snippet looks like this.
<div class="col-sm-$small$ col-md-$medium$ col-lg-$large$">

You’ll notice that there are three variables in this snippet, one for the number of columns at each break point.
Now when I type my abbreviation


My cursor is placed on the first variable, $small$. I type 12 and hit tab. Now my cursor moves to the $medium$ variable and I repeat the process.

All in all, generating a column takes me 9 to 11 key strokes depending on the sizes I use. Now thats an improvement by anyones standards.

One more

Tables are a pain in the ass, there’s no two ways about it. There is a load of code required so this sounds like the prefect candidate for a Live Template to me.

Again, I’m sticking with Bootstrap, I have created the following snippet.

<table class="table table-hover table-bordered table-striped">

In this template I’ve used just four variables but you’ll spot that the $column1title$ and $column2title$ variables are repeated in the table head and foot elements.
PHP Storm will just fill in what I type in the first instance of the variable in the second as well. Cool huh?

And on a side note, since PHPStorm is a code environment if you add tabs or spaces to indent your code the template will honour that for you.

Okay last one, Promise!

Another thing that takes time is forms. So as you can imagine I created some Live Templates for that too!

<div class="form-group">
 <label for="$name$">$Nice_name$</label>
 <input type="$type$" class="form-control" id="$name$" placeholder="Please enter your $placeholder$">

This snippet has a couple of clever bits to it. Firstly, as you type the name of the element the label and ID are filled in.
Then you can choose a type, say email for example.

Now the really clever part is the placeholder and $Nicename$ variables. These makes use of expressions within the Live Template.
They take the $name$ variable and change the first letter to uppercase.
The expression looks like this.


I have recently published my templates on my Github profile

  • Top

A new theme for 2015

Well, its been a while in the making.

I finally got around to updating my sites theme.
While the old one worked well enough, it wasn’t pretty and some may say this new version isn’t a vast improvement. But an improvement it is.

There is almost certainly the odd bug here or there, so should you find anything, feel free to shout up either in the comments or hit me up on twitter at @smileyhcoder

That’s all, why not read an article or two while you’re here.

  • Top

Debugging live sites with Laravel’s middleware

Try as we might sometimes things just don’t work on the live site like they do on your development or staging sites.

Today I had that exact problem. I have made a change to my application and deployed it.
The change doesn’t work on the live site. Awesome!

Read On >

  • Top

NFS exports file is invalid in Vagrant

Vagrant Logo

Sometimes you may come up against a random error message when running “Vagrant Up”. Something like “NFS exports file is invalid

NFS exports file is invalid

Read On >

  • Top

Fetching the last insert ID with Laravel

Its fairly common to need to find the ID of the last inserted record.

You could be adding a product to a table and then adding the product ID to a list of categories. Or a similar process on a blog website.

Read On >

  • Top

Filling HTML select elements in Laravel

Filling a select element or dropdown box is something developers do all the time. In plain old vanilla PHP you do something like this:-

Select elements in vanilla PHP sudo code

- Query the database for the content of the select element
- Loop through the results and write out the <option value="$id">$name</option>

Read On >

  • Top