Adding foreign keys to Laravel’s migrations and schema builder

At work, there was an issue with using Laravel’s migrations and the scheme builder with tables that needed foreign keys. It’s not in the official documents, but after some source code searching, there is a solution that works well…

For example, you have a Users table and each User has Pets (one-to-many). If the User is deleted from the database, you want all their Pets to be deleted as well. In our up method in the migration, we would do something like this:

Schema::table('users', function($table) {
    $table->string('name', 150);

Schema::table('pets', function($table) {
    $table->string('name', 50);

edit: cascade, not cascase. (ht David Stanley)

Laracon: Saturday. 1st Laravel Conference in (others’) Pictures.

Morning in Washington DC




Aaron Kuzemchak : Simple API Development






Dayle Rees : Laravel: An Unexpected Journey





Zack Kitzmiller : Procrastinating Code





Jonathan Barronville : Vagrant, Puppet, Laravel & You





Eric Barnes : The Care and Feeding of a Robot





Shawn McCool : Running a Small Business on Laravel





Taylor Otwell : Eloquence Evolving


There were some awesome talks here at #Laracon. Looking forward to the next!

Some Packagist API “hacks”

In a previous post, I was trying to parse out the most popular Composer packages, and wasn’t able to find a way to get the information through any kind of API. I ended up doing a simple scrape, but then I started searching through the Packagist code ,  and I found some interesting gems.

First, is a list of ALL the packages: . It produces a simple list of all 7002 (at the moment) packages in json.

    "packageNames": [

With that list, you could easily get the specifics about each package at{package-name}.json. For example: . But what about searching? The Packagist website UI isn’t the most intuitive, but there a couple of queries that make the search fairly powerful. First, is just a regular search like : This is fine. It mirrors the site’s search and it’s nice that it includes the ‘downloads’ and ‘favers’

    "results": [
            "name": "laravel/framework",
            "description": "The Laravel Framework.",
            "url": "",
            "downloads": 6493,
            "favers": 4
            "name": "laravel/curl",
            "description": "Laravel Curl Helper Library inspired by Phil",
            "url": "",
            "downloads": 87,
            "favers": 0
    "total": 77,
    "next": ""

But we can get even fancier and search the tags as well:

    "results": [
            "name": "laravel/framework",
            "description": "The Laravel Framework.",
            "url": "",
            "downloads": 6493,
            "favers": 4
            "name": "composer/installers",
            "description": "A multi-framework Composer library installer",
            "url": "",
            "downloads": 5562,
            "favers": 2
            "name": "cartalyst/sentry",
            "description": "PHP 5.3+ fully-featured authentication & authorization system",
            "url": "",
            "downloads": 731,
            "favers": 2
            "name": "illuminate/database",
            "description": "An elegant database abstraction library.",
            "url": "",
            "downloads": 10787,
            "favers": 1
    "total": 60,
    "next": ""

Let’s say we only want packages that are tagged with “laravel” AND “database”. That’s possible, too:[]=laravel&tags[]=database

    "results": [
            "name": "illuminate/database",
            "description": "An elegant database abstraction library.",
            "url": "",
            "downloads": 10787,
            "favers": 1
            "name": "laravelbook/ardent",
            "description": "Self-validating smart models for Laravel 4's Eloquent O/RM",
            "url": "",
            "downloads": 69,
            "favers": 1
            "name": "jtgrimes/laravelodbc",
            "description": "Adds an ODBC driver to Laravel4",
            "url": "",
            "downloads": 5,
            "favers": 0
            "name": "dhorrigan/capsule",
            "description": "A simple wrapper class for the Laravel Database package.  This is only to be used outside of a Laravel application.",
            "url": "",
            "downloads": 79,
            "favers": 0
            "name": "iyoworks/elegant",
            "description": "",
            "url": "",
            "downloads": 12,
            "favers": 0
    "total": 5

You can also search for a “type”, like or even mix the queries like so:[]=orm&tags[]=database

Other interesting ways to view the data can be found at: … so if you wanted to view packages only released in January of 2013, you can use:

My favorite “hack”, is searching with an empty value like so: … which returns all the records (15 on a page), ordered by popularity.

One of these days, if someone else doesn’t beat me to it, I’ll make a review/upvote/downvote site so that the best packages can be found a bit easier. Also, there are some excellent packages that have almost no documentation… so having comments that explain some use-cases would be nice.

Events that get fired in Laravel #laravel

This is really just a reference post for later.  

I needed to hook into eloquent and noticed it was firing an event.  So I was able to add a listener fairly easily.  So I went through the source and made a list of all the fired events  I could find:

  • eloquent.saving
  • eloquent.updated
  • eloquent.created
  • eloquent.saved
  • eloquent.deleting
  • eloquent.deleted
  • eloquent.{event}
  • laravel.query
  • laravel.started {bundle}
  • laravel.resolving (in IOC)
  • laravel.done
  • laravel.log
  • laravel.composing {view}
  • laravel.view.loader
  • laravel.config.loader
  • laravel.language.loader
  • laravel.controller.factory
  • 500
  • 404

The most popular Composer / Packagist PHP packages

There’s no doubt that Composer is the way of the future for PHP, but Packagist (the package archiver) is woefully lacking in useful information.  Well actually, the information is there, there just isn’t a way to get at it.  For example, I was looking for an asset manager and typed in assets, and I couldn’t figure out how they were ordered… and there’s no way to reorder them.

I figured by now, someone MUST have built a user-ratings system for the packages. But after weeks of searching, I haven’t found any. So I figure I might as well start. Right now, I’ve only got a list of all the packages, and they’re ordered by descending total number of downloads:

It shouldn’t be too difficult to add in up and down ratings and comments. The biggest issue is getting the stats.  Packagist doesn’t have an api (that I can see) that exposes the packages’ info, like tags, downloads, and such. The info I have was a quick scrape, and that’s not something I want to keep doing.

So, here are the top 10 PHP composer packages by installs:

Package Description Downloads (as of 12/17/2012)
twig/twig Twig, the flexible, fast, and secure template language for PHP 279,980
symfony/symfony The Symfony PHP framework 231,115
doctrine/common Common Library for Doctrine projects 230,744
doctrine/dbal Database Abstraction Layer 217,669
monolog/monolog Logging for PHP 5.3 198,494
doctrine/orm Object-Relational-Mapper for PHP 197,518
swiftmailer/swiftmailer Swiftmailer, free feature-rich PHP mailer 172,327
kriswallsmith/assetic Asset Management for PHP 166,350
sensio/distribution-bundle The base bundle for the Symfony Distributions 149,974
sensio/framework-extra-bundle This bundle provides a way to configure your controllers with annotations 149,437

Autoloading Organized Routes in Laravel

This is an excellent tip from Jesse O’Brien about breaking up your Laravel routes file.  I’ve actually done something similar for a while now, and kind of forgot that Laravel doesn’t come preconfigured this way.

First, in the application directory, I create another directory called “routes”.

In that directory, I have a “filters.php” and “events.php” and some other files to hold my GET and POST routes.

Then in the start.php, I drop on this bit of code:

foreach (scandir(path('app') . 'routes') as $filename) {
	$path = path('app') . 'routes/' . $filename;
	if (is_file($path)) {

This way, you can add as many routes as you want, and they’ll all load.

I’ve toyed with the idea of scanning for directories in the routes folder, and including those as well… but if you’re at that point, you should probably just use controllers.

Great Read – On Being a Senior Engineer

This is an excellent rundown about what being a “senior” engineer is all about.  Being part of a well-oiled development team, I really try to live up to these standards.  I especially like the “Ten Commandments of Egoless Programming” that he posts:

  1. Understand and accept that you will make mistakes. The point is to find them early, before they make it into production. Fortunately, except for the few of us developing rocket guidance software at JPL, mistakes are rarely fatal in our industry. We can, and should, learn, laugh, and move on.
  2. You are not your code. Remember that the entire point of a review is to find problems, and problems will be found. Don’t take it personally when one is uncovered. (Allspaw note – related: see below, number #10, and the points Theo made above.)
  3. No matter how much “karate” you know, someone else will always know more. Such an individual can teach you some new moves if you ask. Seek and accept input from others, especially when you think it’s not needed.
  4. Don’t rewrite code without consultation. There’s a fine line between “fixing code” and “rewriting code.” Know the difference, and pursue stylistic changes within the framework of a code review, not as a lone enforcer.
  5. Treat people who know less than you with respect, deference, and patience. Non-technical people who deal with developers on a regular basis almost universally hold the opinion that we are prima donnas at best and crybabies at worst. Don’t reinforce this stereotype with anger and impatience.
  6. The only constant in the world is change. Be open to it and accept it with a smile. Look at each change to your requirements, platform, or tool as a new challenge, rather than some serious inconvenience to be fought.
  7. The only true authority stems from knowledge, not from position. Knowledge engenders authority, and authority engenders respect – so if you want respect in an egoless environment, cultivate knowledge.
  8. Fight for what you believe, but gracefully accept defeat. Understand that sometimes your ideas will be overruled. Even if you are right, don’t take revenge or say “I told you so.” Never make your dearly departed idea a martyr or rallying cry.
  9. Don’t be “the coder in the corner.” Don’t be the person in the dark office emerging only for soda. The coder in the corner is out of sight, out of touch, and out of control. This person has no voice in an open, collaborative environment. Get involved in conversations, and be a participant in your office community.
  10. Critique code instead of people – be kind to the coder, not to the code. As much as possible, make all of your comments positive and oriented to improving the code. Relate comments to local standards, program specs, increased performance, etc.

I like to think I live up to most of those, though I’m somewhat (sometimes very) guilty of #9.

Laravel and Redactor

I’ve been working on this book thing, and the bit I wrote about using Laravel with Redactor is quite nice.. if I do say so myself.  Here’s a bit…

First, WYSIWYG text editor javascript libraries are pretty hit and miss. But Redactor is brilliant. It looks good, it’s coded well, and it just works. Using it with Laravel is a PHP dev’s dream.  So to start, we need to make sure we have a copy of Redactor and have Laravel all set up.

In our routes.php file, we create a route to hold our form with the Redactor field

Route::get('redactor', function()
    return View::make('redactor');


Then create a view named redactor.php.  I’m using straight PHP for the form, but Blade would work just as well.

<!DOCTYPE html>
         <title>Laravel and Redactor</title>
         <meta charset="utf-8">
         <link rel="stylesheet" href="css/redactor.css" />
         <script src="//"></script>
         <script src="js/redactor/redactor.min.js"></script>
         <?php echo Form::open() ?>
         <?php echo Form::label('mytext', 'My Text') ?>
         <?php echo Form::textarea('mytext', '', array('id' => 'mytext')) ?>
         <?php echo Form::submit('Send it!') ?>
         <?php echo Form::close() ?>
         <script type="text/javascript">
               $(function() {
                           imageUpload: 'redactorupload'

So we created a textarea with the name ‘mytext’, and make the id of that field the same as the name.  So to target it, and add Redactor to it, just use


In the imageUpload parameter, we pass the URL path where we post the image. In this case, it’s routing to ‘redactorupload’.  So let’s create that route.

Route::post('redactorupload', function()
   $rules = array(
         'file' => 'image|max:10000'

   $validation = Validator::make(Input::all(), $rules);
   $file = Input::file('file');
   if ($validation->fails())
        return FALSE;
         if (Input::upload('file', 'public/images', $file['name']))
            return Response::json(array('filelink' => 'images/' . $file['name']));
         return FALSE;

The image will automatically POST here. So we want to make sure it’s actually an image and is less than 10 megabytes… so we run those validations. If everything validates, we move it to its permanent location, and send out a json response.  Redactor expects the json key to be ‘filelink’ and the value to be the path to the image.  If everything worked, when you add the image, it will display in your Redactor textarea.

We can check what the code output looks like by creating a route to accept the Redactor data.

Route::post('redactor', function()
    return dd(Input::all());

File uploads through redactor are done pretty much the same way, except with the fileUpload parameter… and the json output should also include a ‘filename’ key.

Postmark – Laravel bundle

I did a Laravel bundle for the Postmark API.  It’s really just a simple wrapper for the API, and I needed it for a non-Laravel project I worked on, and noticed there wasn’t a bundle already. Probably the one update that would be most useful is getting attachments working.  Right now, you have to parse the content and mime-type before attaching… and I should probably update it to just accept the file and do all the parsing in the method. Maybe one day.

Setting up a virtual host for WAMP and Laravel

Normally when I start a new web project, I just use “http://localhost/project_name_here” as the URL I run, and that’s worked for me. But recently, I started learning and working in Laravel, and one of the…uh… features, is that you have to navigate to the “public” folder.  So your URL would be “http://localhost/project_name_here/public”.  That was fine while I was learning, but I’m about to start a new project, and I don’t want that “public” in there.

I first thought about modifying the htaccess file and putting the “public/index.php” file into the root and changing the paths, but I decided to go the Apache VirtualHost route. Of course, since I’m using WAMP, most of the suggestions about VirtualHosts, like from Code Happy,  don’t apply… and searching for WAMP VirtualHost shows as many solutions as there are results.  So here’s what I did…

1) Go into your WAMP Apache config files.  My wamp is located a c:/wamp, so the path to my config files is C:/wamp/bin/apache/Apache2.2.17/conf

     a) open httpd.conf in a text editor
     b) located the line

#Include conf/extra/httpd-vhosts.conf

And remove the first “#”
     c)  go into the extra folder, and edit the httpd-vhosts.conf file.  Here’s what I added..

<VirtualHost *:80>
DocumentRoot "C:/Users/Terry/Dropbox/www/project_name/public"

<Directory "C:/Users/Terry/Dropbox/www/project_name/public">
Options Indexes FollowSymLinks
AllowOverride all
# onlineoffline tag - don't remove
Order Deny,Allow
Deny from all
Allow from

     d) restart the Apache service

2) Edit the windows host file.
     a) go into C:/Windows/System32/drivers/etc and open the file “hosts” in a text editor.
     b)  Just add one line:

That got everything working perfectly for me.