My Journey writing a Laravel Book

It all started 2 years ago, when I found this post on Forrst (archived.org) by Taylor Otwell announcing the release of Laravel 2.  I downloaded and tried it.  As I was using Codeigniter at the time, I found it quite nice and refreshingly different. However, my job only had PHP 5.2 on its server, so I only tried it locally and didn’t go much further. Then a few months later, he announced version 3 and I gave it more time.  When version 3.1 was released, I ended up using it for some personal projects and read through the source code pretty extensively. At that point, I considered myself fairly ‘expert’ in Laravel.

In August of 2012, I was contacted by Packt Publishing to be a ‘technical reviewer’ for Shawn McCool‘s Laravel Starter book. It was a fairly easy thing, and payment was basically just a hard copy of the book and my name/bio in it. When it was released, I was pretty excited to see my name in print. This was my basic reaction.

Shortly thereafter, I was contacted again by Packt with the offer to write a Laravel book, specifically a ‘cookbook‘.  It seemed like a daunting task, but I figured it would be a great step in my career, so I agreed.  The money isn’t great, but since I’m fairly unknown and payment was guaranteed, I was pretty happy with the compensation.

Packt pumps out tons of niche tech books every month, so they have a solid system set in place.  The first step was an outline. I had to come up with chapters, and then ‘recipes’ for those chapters with an estimated page count.  At this point, I started to realize that page counts and recipe counts were a pretty big deal to them.  They wanted 11 – 12 chapters with 9 or 10 recipes in each.  They said it looks good to have ‘over 100 recipes’ on the cover.   I struggled a bit at first, since I had done absolutely nothing like this, ever.  Eventually, after reading forum posts and seeing IRC questions, I began to get an understanding of what people needed help with.  It made the outline process a bit easier.

With the outline complete and approved by Packt, I began working on the chapters.  It was actually a lot easier than I first thought.  The only real issue I had was how the whole thing was formatted.  You get a Word document template, and you’re supposed to format everything with their pre-made styles. Formatting is VERY important to them. Also, everything is supposed to be worded like “and then we do this” or “so our next step is” because I guess it makes the reader feel part of the book or something. Formatting was probably the most stressful part of the initial process.

Chapters 1 to 9 actually went fairly easily. At this point in January 2013, version 4 of Laravel had already been announced, and the beta release was on Laravel’s develop branch on GitHub.  Then someone who was doing a technical review asked if this was for version 3 or version 4.  Packt asked me about it, and I told them I was working on L3, since L4 was still in early beta.  But most people’s best guess was a summer release of L4, and it would be quite a bit different from L3.  Packt and I decided it would be best to wait, because the release date for the book would probably be around the time L4 was released… and thus would instantly be irrelevant.

Now, it’s the end of February and I go to Laracon in DC. It was a fun time and I got to meet some excellent people. We also find out that L4 would be released in May.  So now, all I needed to do was learn L4.  With work and family, it wasn’t very easy to dig that deep into version 4.  The source is pretty extensive and relies on a lot of 3rd party libraries.  Packt was pretty urgent about wanting the thing finished, so I decided to stick with the original outline, salvage what I could, and just update the syntax for L4.  A few chapters needed a major overhaul, like one I wrote about using and creating L3 Bundles or how to include and use Composer in an L3 app. There are some that are still in the book, and work, but are kind of silly to do when using L4… for example, installing L4 as a git submodule.  Unfortunately, there are also a couple of DGAF chapters, like 3 separate chapters on using Twitter/Facebook/Linkedin for auth/logging in.  I ended up just getting it done and turning it in, and trying to make it as good as it could be.  I fell short of the 100+ recipes by 10 or so, and the 300+ pages by about 50.  Oh well. By the end of October, the Laravel Application Development Cookbook was officially published.  I can now call myself an author.

Now that I’ve actually spent some time with L4 and competed some projects with it, I’m kind of sad that there are certain bits missing.  Things like using the Laravel workbench, or creating custom commands, or service providers. I would add, update, or replace a good 20% of the book if I were to re-do it today.

Having said that, I still think it’s worth the money you pay, especially for the hard copy. Even just the ebook is less $ than two of the more popular Laravel ebooks available at the moment, and I think the information contained is just as valid. And while some may not have a great opinion about Packt, I was overall fairly happy with them.  I think their focus on page counts and formatting makes the process a little less enjoyable, but they promised a certain payment at various points in the process, and they delivered in a timely manner.

I think Packt is great for an unknown with a decent amount of knowledge on a subject, especially if you’ve never written anything before. Just having a published book on Amazon has opened a few doors for me, and I’ve seen an uptick in blog readers and Twitter followers. Though, if you’re even remotely known for a particular subject, just go to LeanPub… where you would need to just sell 150 books at $20.

In closing… I got my name on a book, I got a nice printed dedication to my wife and kid, and I got a little money.  So I’m pretty happy with the experience.  I mean, I may never do it again… but I’m happy I did it once.

 

Laravel Application Development Cookbook

Hey look! I wrote a book about Laravel: http://bit.ly/laravelcookbook

Some of the fun and exciting things you’ll learn…

  • Setting Up and Installing Laravel
  • Using Forms and Gathering Input
  • Authenticating Your Application
  • Storing Data
  • Using Controllers and Routes for URLs and APIs
  • Displaying Your Views
  • Creating and Using Composer Packages
  • Using Ajax and jQuery
  • Using Security and Sessions Effectively
  • Testing and Debugging Your App
  • Deploying and Integrating Third Party Libraries

 

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->increments('id')->unsigned();
    $table->string('email');
    $table->string('name', 150);
    $table->timestamps();
});

Schema::table('pets', function($table) {
    $table->increments('id')->unsigned();
    $table->integer('user_id')->unsigned();
    $table->string('name', 50);
    $table->foreign('user_id')->references('id')->on('users')->onDelete('CASCADE')->onUpdate('CASCADE');
});

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

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

Morning in Washington DC

 

 



 

Aaron Kuzemchak : Simple API Development

Demo

 

 

 



 

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: https://packagist.org/packages/list.json . It produces a simple list of all 7002 (at the moment) packages in json.

{
    "packageNames": [
        "illuminate/auth",
        "illuminate/cache",
        "illuminate/config",
        "illuminate/console",
        "illuminate/container",
        "illuminate/cookie",
        "illuminate/database",
        "illuminate/encryption",
        "illuminate/events",
        "illuminate/exception",
        "illuminate/filesystem",
        "illuminate/foundation",
        "illuminate/hashing",
        "illuminate/http",
        "illuminate/log",
        "illuminate/mail",
        "illuminate/pagination",
        "illuminate/queue",
        "illuminate/redis",
        "illuminate/routing",
        "illuminate/session",
        "illuminate/socialite",
        "illuminate/support",
        "illuminate/translation",
        "illuminate/validation",
        "illuminate/view",
        "illuminate/workbench",
    ]
}


With that list, you could easily get the specifics about each package at https://packagist.org/p/{package-name}.json. For example: https://packagist.org/p/illuminate/database.json . 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 : https://packagist.org/search.json?q=laravel 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": "https://packagist.org/packages/laravel/framework",
            "downloads": 6493,
            "favers": 4
        },
        {
            "name": "laravel/curl",
            "description": "Laravel Curl Helper Library inspired by Phil",
            "url": "https://packagist.org/packages/laravel/curl",
            "downloads": 87,
            "favers": 0
        },
    ],
    "total": 77,
    "next": "https://packagist.org/search.json?q=laravel&page=2"
}

But we can get even fancier and search the tags as well: https://packagist.org/search.json?tags=laravel

{
    "results": [
        {
            "name": "laravel/framework",
            "description": "The Laravel Framework.",
            "url": "https://packagist.org/packages/laravel/framework",
            "downloads": 6493,
            "favers": 4
        },
        {
            "name": "composer/installers",
            "description": "A multi-framework Composer library installer",
            "url": "https://packagist.org/packages/composer/installers",
            "downloads": 5562,
            "favers": 2
        },
        {
            "name": "cartalyst/sentry",
            "description": "PHP 5.3+ fully-featured authentication & authorization system",
            "url": "https://packagist.org/packages/cartalyst/sentry",
            "downloads": 731,
            "favers": 2
        },
        {
            "name": "illuminate/database",
            "description": "An elegant database abstraction library.",
            "url": "https://packagist.org/packages/illuminate/database",
            "downloads": 10787,
            "favers": 1
        }
    ],
    "total": 60,
    "next": "https://packagist.org/search.json?page=2&tags%5B0%5D=laravel"
}


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

{
    "results": [
        {
            "name": "illuminate/database",
            "description": "An elegant database abstraction library.",
            "url": "https://packagist.org/packages/illuminate/database",
            "downloads": 10787,
            "favers": 1
        },
        {
            "name": "laravelbook/ardent",
            "description": "Self-validating smart models for Laravel 4's Eloquent O/RM",
            "url": "https://packagist.org/packages/laravelbook/ardent",
            "downloads": 69,
            "favers": 1
        },
        {
            "name": "jtgrimes/laravelodbc",
            "description": "Adds an ODBC driver to Laravel4",
            "url": "https://packagist.org/packages/jtgrimes/laravelodbc",
            "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": "https://packagist.org/packages/dhorrigan/capsule",
            "downloads": 79,
            "favers": 0
        },
        {
            "name": "iyoworks/elegant",
            "description": "",
            "url": "https://packagist.org/packages/iyoworks/elegant",
            "downloads": 12,
            "favers": 0
        }
    ],
    "total": 5
}


You can also search for a “type”, like https://packagist.org/search.json?type=symfony-module or even mix the queries like so: https://packagist.org/search.json/?q=laravel&tags[]=orm&tags[]=database

Other interesting ways to view the data can be found at: https://packagist.org/packages.json … so if you wanted to view packages only released in January of 2013, you can use: https://packagist.org/p/packages-2013-01.json

My favorite “hack”, is searching with an empty value like so: https://packagist.org/search.json?page=1&q= … 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: http://matu.la/packages/

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)) {
		require($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>
<html>
   <head>     
         <title>Laravel and Redactor</title>
         <meta charset="utf-8">
         <link rel="stylesheet" href="css/redactor.css" />
         <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
         <script src="js/redactor/redactor.min.js"></script>
   </head>
   <body>
         <?php echo Form::open() ?>
         <?php echo Form::label('mytext', 'My Text') ?>
         <br>
         <?php echo Form::textarea('mytext', '', array('id' => 'mytext')) ?>
         <br>
         <?php echo Form::submit('Send it!') ?>
         <?php echo Form::close() ?>
         <script type="text/javascript">
               $(function() {
                     $('#mytext').redactor({
                           imageUpload: 'redactorupload'
                     });
               });
         </script>
   </body>
</html>

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

$('#mytext').redactor();

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;
    }
    else
    {
         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.