Laravel routes – Generating a CSV

We’re currently building out an API at Basanty, and I was looking for a way to generate a simple Excel/CSV file.  Using the `artisan routes` command, you can print out a nice table in the console, or even save it by appending `> routes.txt`. The problem is the Symfony table formatter doesn’t translate well to a document.

So I created a simple route that loops through the routes, and saves them to a csv file.  This could quite easily be abstracted to a custom artisan command. Also, after generating the file, you should probably remove it immediately.

/**
 * Generate a CSV of all the routes
 */
Route::get('r', function()
{
    header('Content-Type: application/excel');
    header('Content-Disposition: attachment; filename="routes.csv"');

    $routes = Route::getRoutes();
    $fp = fopen('php://output', 'w');
    fputcsv($fp, ['METHOD', 'URI', 'NAME', 'ACTION']);
    foreach ($routes as $route) {
        fputcsv($fp, [head($route->methods()) , $route->uri(), $route->getName(), $route->getActionName()]);
    }
    fclose($fp);
});

How I use Bower and Grunt with my Laravel projects

I just ran across an excellent article on how to use Grunt with Laravel, and I thought I’d share my process. First things first… install node, npm, bower, grunt, and all that. Google it if this is new to you.

With Laravel installed, I actually use the Laravel-Assetic package for all my concatenation and minimization. That way, cacheing is taken care of automatically. Here’s my composer,json file with all the needed filters

"require": {
		"laravel/framework": "4.0.*",
		"slushie/laravel-assetic": "dev-master",
		"leafo/lessphp": "dev-master",
		"lmammino/jsmin4assetic": "1.0.*",
		"natxet/CssMin": "dev-master"
},

Next, I use Bower for all my asset dependencies. To specify where the files are saved, I needed to add a .bowerrc file in my app’s root, and added this

{
	"directory": "assets/bower"
}

I add the files to use in my bower.json file

{
  "name": "Matula",
  "version": "0.0.0",
  "homepage": "https://terrymatula.com",
  "authors": [
    "Matula <terrymatula@gmail.com>"
  ],
  "license": "MIT",
  "ignore": [
    "**/.*",
    "node_modules",
    "bower_components",
    "test",
    "tests"
  ],
  "dependencies": {
    "underscore": "~1.4.4",
    "Eventable": "~1.0.1",
    "jquery": "~2.0.3",
    "bootstrap": "jasny/bootstrap#~3.0.1-p7",
    "sir-trevor-js": "~0.3.0",
    "jquery-ui": "~1.10.3",
    "angular": "~1.2.2"
  },
  "resolutions": {
    "jquery": "~2.0.3"
  }
}

In the command line, run `bower install` and all those files are added to the ‘assets/bower’ directory. Then (after following the Laravel-Assetic install instructions) we need to add the files to use in the Laravel-Assetic config file. Here’s an example of my config:

<?php
/**
 * Configure laravel-assetic options in this file.
 *
 * @package slushie/laravel-assetic
 */

return array(
  'groups' => array(
    // Javascripts
    'script' => array(
      'filters' => array(
        'js_min'
      ),
      'assets' => array(
        'underscore',
        'eventable',
        'jquery',
        'jqueryui',
        'redactorjs',
        'bootstrapjs',
        'sirtrevorjs',
        'sirtrevorcustomjs',
        'customjs'
      ),
      'output' => 'js/matula.js'
    ),

    // CSS
    'style' => array(
      'filters' => array(
        'css_min'
      ),
      'assets' => array(
        'bootstrapcss',
        'sirtrevoricons',
        'sirtrevorcss',
        'redactorcss',
        'customcss'
      ),
      'output' => 'css/matula.css'
    ),

    // LESS files
    'less' => array(
      // Convert LESS to css
      'filters' => array(
        'less',
        'css_min'
      ),
      'assets' => array(
        public_path('less/style.less'),
      ),
      'output' => 'css/less.css'
    ),
  ),

  'filters' => array(
    // Filters
    'js_min'  => 'Assetic\Filter\JsMinFilter',
    'css_min' => 'Assetic\Filter\CssMinFilter',
    'less'    => 'Assetic\Filter\LessphpFilter'
  ),

  // List of Assets to Use
  'assets' => array(
    // Add name to assets
    'jquery'            => public_path('bower/jquery/jquery.js'),
    'angular'           => public_path('bower/angular/angular.js'),
    'bootstrapjs'       => public_path('bower/bootstrap/dist/js/bootstrap.js'),
    'eventable'         => public_path('bower/Eventable/eventable.js'),
    'jqueryui'          => public_path('bower/jquery-ui/ui/jquery-ui.js'),
    'jqueryfileapi'     => public_path('bower/jquery.fileapi/jquery.fileapi.js'),
    'sirtrevorjs'       => public_path('bower/sir-trevor-js/sir-trevor.js'),
    'underscore'        => public_path('bower/underscore/underscore.js'),
    'sirtrevorcustomjs' => public_path('js/custom/sir-trevor-custom-blocks.js'),
    'redactorjs'        => public_path('js/custom/redactor.js'),
    'customjs'          => public_path('js/custom/bs.js'),

    'bootstrapcss'      => public_path('bower/bootstrap/dist/css/bootstrap.css'),
    'sirtrevoricons'    => public_path('bower/sir-trevor-js/sir-trevor-icons.css'),
    'sirtrevorcss'      => public_path('bower/sir-trevor-js/sir-trevor.css'),
    'redactorcss'       => public_path('css/custom/redactor.css'),
    'customcss'         => public_path('css/custom/custom.css'),
    'customless'        => public_path('less/*')
  )
);

Some explanation: Starting at the bottom, we have our ‘assets’ array, where we assign a name to each asset and point it to the file we want to use. Then, we have our ‘filters’ array where we give a name to each filter we’re using. The composer file loaded in the filters we’re using. Before that, we create our ‘groups’ array. Each group is basically the filters we want to use, the files we want to filter, and then the output file to create. The order of the files is important, since this will affect any dependent files (eg, jquery needs to be before jquery-ui).

Now, we can run `php artisan asset:warm’ and all our files will be created. The one issue I had during development was that I was doing lots of quick updates to the css/js, and it would take time for the asset cache to clear. So I had to ‘warm’ them often. This was a time waste, so I’m using grunt to take care of that for me, ad live-reload it as well.

The only 2 grunt packages we need are ‘grunt-contrib-watch’ and ‘grunt-exec’. This is how my Gruntfile.js file looks:

module.exports = function(grunt) {

  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),

    exec: {
      warmscript: {
        cmd: 'php artisan asset:warm script'
      },
      warmstyle: {
        cmd: 'php artisan asset:warm style'
      },
      warmless: {
        cmd: 'php artisan asset:warm less'
      }
    },
    watch: {
      options: {
        livereload: true
      },
      less: {
        files: ['assets/less/*.less'],
        tasks: ['exec:warmless']
      },
      css: {
        files: ['assets/css/custom/*.css'],
        tasks: ['exec:warmstyle']
      },
      js: {
        files: ['assets/js/custom/*.js'],
        tasks: ['exec:warmscript']
      },
      html: {
        files: ['app/views/*.php', 'app/views/**/*.php']
      }
    }
  });

  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.loadNpmTasks('grunt-exec');

  grunt.registerTask('default', ['exec', 'watch']);

};

I open a dedicated command line tab, run `grunt` and it will warm everything on start. Then, anytime I make a change to one of the files, it’s automatically warmed and the page is reloaded. The ‘html’ part will reload it when my views are changed.

One word of warning… the way I have it set up, it loads every js/css into every view. While it’s handy to only have 2 (or 3 in my case) minimized files that need to be loaded, we’ll only need Redactor on the pages with forms.  It might be best to create our groups dynamically, and only use the assets we need for each view.

My Journey writing a Laravel Book

It all started 2 years ago, when I found this post on Forrst 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’ll 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.