Conditional Insert / Update With The Eloquent ORM

I have been using Laravel more and more lately (full post on that coming soon) and have really been enjoying the Eloquent ORM. I plan to extend the ORM so that it includes an "upsert" method but in the short term I had a need to check for the existence of a key and then conditionally update or insert a record into the model. There are some very easy ways to do this using Fluent (also built-in to Laravel) but I wanted to stick with a completely Eloquent-based solution so here is what I came up with:

You could reduce the number of lines in that code by using the ternary operator but I find the syntax above much easier to read and better for example purposes.

In my model I have my $key set to the email column in my database which is why I am passing that to the find() method.

As I mentioned above I plan to put together a full post about Laravel soon so stay tuned!

Extend PHP error_log() Functionality

Throughout development many of us use the built-in error_log() function quite a bit. I know I sure do when I am debugging models, controllers, and the such but don't you hate it when you want to write the contents of an array or object to the error log? The error_log() function only accepts a string parameter so we have to use a little trick when we want to output array/object contents. We can accomplish this using only a few lines of code:

While this is nothing ground breaking, it's certainly a handy trick when you are trying to debug code that deals with arrays and objects.

The World In Links [April, 2012] -- Code, Mobile, Ruby

The World In Links by Nicholas Kreidberg Code - My recently updated projects on Github.
Github - Instantly Beautiful Project Pages.
HTML5 - Toying w/ the HTML5 File System API.
Lifestyle - 8 tips to simplify your work life.
Mobile Security - The top 10 Security Tools For Your Smartphone.
MongoDB - A year with Mongo.
Monitoring - Monitor your Website’s Uptime with Google Docs.
Phono - A simple jQuery plugin and JavaScript library that turns the browser into a phone.
Photography - A showcase of landscape photography.
Ruby - Teach your children Ruby with Kidsruby.
Snippets - Awesome sites to find useful code snippets.
WordPress - Useful action hooks and filters.