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!

The World In Links [11/21-11/27/2011] -- CodeIgniter, Firebug, MongoDB

The World In Links by Nicholas Kreidberg Chrome: Game changing performance increase with new garbage collection routine.

CodeIgniter: Easy package management using Sparks.

CSS: Creating style sheets for print.

Firebug: A guide for using Firebug from a design perspective.

Google+: 10 productive things you should be doing.

jQuery: 10 awesome snippets.

MongoDB: A getting started tutorial.

MySQL: Generate complete Excel spreadsheet using a database.

PostgreSQL: Heroku launches cloud-based database-as-a-service.

Ruby: Installing Rails and MySQL on Lion.

Tools & Toys: The 2011 Christmas catalog.

Web Development: Injecting custom HTML and CSS into an iFrame.

The World In Links [9/26-10/9/2011] -- Apple, Facebook, JavaScript

The World In Links by Nicholas Kreidberg Apple: A timeline/tribute to Steve Jobs.

Coding: 7 crazy tips to make you a better coder.

Database: 17 techniques used to scale turntable.fm to millions of users.

Facebook: Design and code your first integrated Facebook application.

HTML5: A beginners guide to building CSS3/HTML5 webpages.

iPhone 4S: Everything you need to know from the announcement in one spot.

JavaScript: 20 frameworks worth checking out.

jQuery UI: Why you should be excited about version 1.9.

Photography: A collection of photos featuring facial manipulation.

Podcasts: A list of solid web design/development podcasts.